Python Data Types with examples|

In this article we are going to discuss python data types with examples, python data type list, how many data types in python, data types in python with examples, python data type list and many more. so keep reading the article till last.

data types in python
data types in python

Data Types in Python

Data types in Python are like the different flavours of ice cream. Just as you choose between chocolate, vanilla, or strawberry, Python programmers choose data types to give structure and meaning to their data.

Imagine you’re working with numbers. You’d use the int data type for whole numbers, like 5 or -10. But what if you need to deal with numbers that have decimal points? That’s where the float data type comes in, handling numbers like 3.14 or -0.5.

Now, think about words and text. Python uses the str (string) data type for these. Whether it’s your name, a message, or a book title, they all fit into the str category.

And what about collections of things, like a shopping list? Python provides list and tuple data types for these. Lists are like your grocery list – you can change what’s on it. Tuples, on the other hand, are like a sealed letter – once you write it, you can’t change it.

Do you want to pair things up, like a dictionary definition? Python’s got a data type for that too – it’s called dict. It’s like having a word and its explanation side by side.

There’s even a special data type called bool for answering yes-or-no questions. Think of it as a binary switch – it’s either “True” or “False.”

And this is just the beginning. Python has more data types to handle sets, complex numbers, and even your own custom data types. Each of these data types helps you make sense of the data you work with, making Python a versatile language for all sorts of tasks.

In this journey through data types in Python, we’ll explore each type in detail, showing you how they work and how to use them effectively. By the end, you’ll have a deeper understanding of the flavors Python offers for your data, helping you become a more skilled Python programmer. So, let’s start our data type adventure!

Types of Data Types in Python

Built-in Data Types

  • Numeric Types:
    • Integers (int)
    • Floating-Point Numbers (float)
    • Complex Numbers (complex)
  • Sequence Types:
    • Lists (list)
    • Tuples (tuple)
    • Strings (str)
  • Mapping Type:
    • Dictionaries (dict)
  • Set Types:
    • Sets (set)
  • Boolean Type:
    • Boolean (bool)

Numeric Data Types in Python

In the world of programming, numbers are fundamental. Whether you’re counting items, calculating measurements, or dealing with mathematical operations, numbers are at the core of many tasks. Python, being a versatile language, offers several numeric data types to handle different kinds of numerical values.

Integers (int)

Integers, denoted by the int data type, are whole numbers without decimal points. They can be positive or negative, such as -3, -2, 0, 1, 42, or even 1000000. Integers are ideal for tasks like counting items or representing indices in a list.

Integers are whole numbers without decimal points. They can be positive or negative.

age = 25
quantity = -10
days_in_week = 7
population = 789456123

Example :

num1 = 20
num2 = 40

add = num1 + num2
print(add)    //  result will be "60"

sub = num1 - num2
print(sub)    // result will be "-20"

mul = num1 * num2 
print(mul)    // result will be "800"

Floating-Point Numbers (float)

When you need to work with numbers that have decimal points or fractions, you turn to floating-point numbers, represented by the float data type. These numbers can be as simple as 3.14 or more complex like 0.3333333333333333.

pi = 3.14159
temperature = -5.5
price = 19.99
weight = 0.0035

Example :

num1 = 3.5
num2 = 6.3

print(num1+num2)   // result wil be "9.8"
print(num1-num2)    // result will be "-2.8"
print(num1*num2)   // result will be "2205"
print(num1/num2)   // result will be "0.555555.."

Complex Numbers (complex)

Python even accommodates complex numbers, a combination of a real part and an imaginary part, which are represented using the complex data type. Complex numbers are particularly useful in scientific and engineering applications.

In Python, a complex number is created by specifying a real part and an imaginary part, both separated by a + or - sign, followed by the letter j. The real part represents the actual number, and the imaginary part is a multiple of the imaginary unit j, where j is defined as the square root of -1.

Syntax :

complex_number = real_part + imaginary_part * j

Example :

z1 = 3 + 4j
z = 3 + 4j  # 3 is the real part, 4j is the imaginary part
z1 = 3 + 4j  # 3 is the real part, 4j is the imaginary part
z2 = -2.5 - 1.2j  # -2.5 is the real part, -1.2j is the imaginary part

Python supports various operations with complex numbers, including addition, subtraction, multiplication, and division. These operations work in a natural way, taking into account both the real and imaginary parts.

Addition :

z1 = 3 + 4j
z2 = 1 - 2j
result = z1 + z2
print(result)  # Output: (4+2j)

Substraction :

z1 = 3 + 4j
z2 = 1 - 2j
result = z1 - z2
print(result)  # Output: (2+6j)

Multiplication :

z1 = 2 + 3j
z2 = 1 + 2j
result = z1 * z2
print(result)  # Output: (-4+7j)

Devision :

z1 = 6 + 2j
z2 = 2 - 1j
result = z1 / z2
print(result)  # Output: (3+2j)

Sequence Data Types In Python

List Data Type In Python

The list is a versatile and fundamental data type in Python. It is used to store collections of items, which can be of different data types (including other lists). Lists are mutable, meaning you can change their content (add, remove, or modify elements) after they are created. Let’s explore the Python list data type with examples:

Creating Lists

You can create a list by enclosing a comma-separated sequence of values within square brackets [].

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed_list = ["apple", 3.14, 42, True]
empty_list = []

In these examples:

  • fruits is a list of strings.
  • numbers is a list of integers.
  • mixed_list contains a mix of data types.
  • empty_list is an empty list.

Accessing Elements

You can access individual elements of a list using indexing. Python uses 0-based indexing, meaning the first element is at index 0, the second at index 1, and so on.

fruits = ["apple", "banana", "cherry"]
first_fruit = fruits[0]  # Access the first element (apple)
second_fruit = fruits[1]  # Access the second element (banana)

Modifying Lists

Lists are mutable, so you can change their content by assigning new values to specific elements or by using various list methods.

fruits = ["apple", "banana", "cherry"]
fruits[0] = "orange"  # Modify the first element
fruits.append("grape")  # Add an element to the end
fruits.remove("banana")  # Remove a specific element
fruits.pop()  # Remove the last element

List Slicing

You can extract a portion of a list using slicing. Slicing allows you to create a new list containing a subset of the original elements.

numbers = [1, 2, 3, 4, 5]
subset = numbers[1:4]  # Create a new list with elements 2, 3, and 4

List Methods

Python provides a variety of methods for working with lists, including append(), extend(), insert(), remove(), pop(), index(), count(), sort(), and reverse(). These methods allow you to perform common list operations efficiently.

numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort()  # Sort the list in ascending order
numbers.reverse()  # Reverse the list

Tuple Data Type in Python

A tuple in Python is an ordered, immutable (unchangeable) collection of elements enclosed in parentheses (). Tuples are quite similar to lists, but the key difference is that once you create a tuple, you cannot modify its elements. Tuples are used when you want to store a collection of items that should not change during the course of your program.

Creating Tuples

To create a tuple, you can use parentheses and separate the elements with commas. Here’s an example:

fruits = ('apple', 'banana', 'cherry')

Accessing Elements

You can access elements in a tuple using indexing, just like in lists. Indexing starts at 0 for the first element:

first_fruit = fruits[0]  # Access the first element ('apple')

Iterating Through a Tuple

You can iterate through a tuple using a for loop:

for fruit in fruits:
    print(fruit)

Tuple Length

To find the number of elements in a tuple, you can use the len() function:

num_fruits = len(fruits)  # This will be 3 in our example

Tuple Packing and Unpacking

Tuples allow for packing multiple values into a single variable:

coordinates = (5, 3)  # Tuple packing

Immutability

Tuples are immutable, which means you cannot change their elements once they are created. For example, the following code will result in an error:

fruits[0] = 'orange'  # This will raise a TypeError

Use Cases for Tuples

Tuples are useful in various scenarios:

  • Storing related pieces of data together (e.g., coordinates).
  • When you want to ensure that the data remains unchanged.
  • As keys in dictionaries (since they are immutable).

Example

Here’s a more practical example of using tuples to store information about a person:

person = ('John', 30, 'john@example.com')

# Accessing elements
name = person[0]
age = person[1]
email = person[2]

# Iterating through the tuple
for info in person:
    print(info)

# Tuple packing and unpacking
address = ('123 Main St', 'City', 'Country')
street, city, country = address

# Immutability (This will raise a TypeError)
person[1] = 31

String Data Type in Python

Certainly! The string data type in Python is used to represent text or sequences of characters. Strings are one of the most commonly used data types in programming. Let’s explore the string data type with examples:

Creating Strings

You can create strings in Python by enclosing text within either single (‘ ‘), double (” “), or triple (”’ ”’ or “”” “””) quotation marks. Here are examples:

# Using single quotes
single_quoted = 'Hello, World!'

# Using double quotes
double_quoted = "Python Programming"

# Using triple quotes for multi-line strings
multi_line = '''This is a
multi-line
string.'''

Accessing Characters in a String

You can access individual characters within a string using indexing. Indexing in Python starts from 0.

text = "Python"

# Accessing individual characters
first_char = text[0]  # 'P'
second_char = text[1]  # 'y'

String Concatenation

You can combine (concatenate) strings using the + operator.

first_name = "John"
last_name = "Doe"

full_name = first_name + " " + last_name  # "John Doe"

String Length

You can find the length of a string (the number of characters) using the len() function.

text = "Hello, World!"
length = len(text)  # 13

String Methods

Python offers numerous built-in string methods for various operations. Here are a few examples:

text = "python is easy to learn"

# Capitalize the first letter
capitalized = text.capitalize()  # "Python is easy to learn"

# Convert to uppercase
uppercase = text.upper()  # "PYTHON IS EASY TO LEARN"

# Replace "easy" with "fun"
replaced = text.replace("easy", "fun")  # "python is fun to learn"

Mapping Type

Dictionary Data Type in Python

A dictionary in Python is a versatile and fundamental data type that allows you to store and retrieve data in a structured way. Unlike sequences like lists and tuples, dictionaries use a key-value pair system, where each value is associated with a unique key. Dictionaries are defined using curly braces {} and consist of key-value pairs separated by colons :.

Characteristics of Dictionaries:

  • Unordered: Dictionaries do not maintain a specific order of elements, unlike lists.
  • Mutable: You can change, add, or remove key-value pairs in a dictionary.
  • Key-Value Pairs: Each element in a dictionary consists of a key and its associated value.
  • Keys are Unique: Keys must be unique within a dictionary. Duplicate keys are not allowed.
  • Keys are Immutable: Keys can be of immutable data types like strings, numbers, or tuples.

Creating a Dictionary:

Here’s how you create a dictionary in Python:

# Dictionary of person's information
person = {
    'name': 'Alice',
    'age': 30,
    'city': 'New York'
}

In this example, we have a dictionary called person with three key-value pairs: 'name', 'age', and 'city'.

Accessing Values:

You can access values in a dictionary by referring to their keys:

# Accessing values
print(person['name'])  # Output: 'Alice'
print(person['age'])   # Output: 30

Modifying and Adding Key-Value Pairs:

Dictionaries are mutable, so you can change values or add new key-value pairs:

# Modifying values
person['age'] = 31

# Adding a new key-value pair
person['job'] = 'Engineer'

Removing Key-Value Pairs:

You can remove key-value pairs using the del statement:

# Removing a key-value pair
del person['city']

Dictionary Methods:

Python provides several methods for working with dictionaries, including keys(), values(), and items() for accessing keys, values, and key-value pairs, respectively.

# Getting keys, values, and items
keys = person.keys()     # Returns: dict_keys(['name', 'age', 'job'])
values = person.values() # Returns: dict_values(['Alice', 31, 'Engineer'])
items = person.items()   # Returns: dict_items([('name', 'Alice'), ('age', 31), ('job', 'Engineer')])

Example Use Case:

Dictionaries are commonly used to represent structured data, such as configurations, user profiles, and more. Here’s an example of a user profile dictionary:

user_profile = {
    'username': 'jsmith',
    'email': 'jsmith@example.com',
    'age': 28,
    'is_active': True
}

Set Data Type in Python

Certainly! In Python, a set is a built-in data type that represents an unordered collection of unique elements. Sets are defined using curly braces {} or by using the set() constructor.

Here’s an explanation of sets in Python with examples:

1. Creating a Set

You can create a set by enclosing a comma-separated sequence of elements within curly braces {}. Alternatively, you can use the set() constructor.

fruits = {"apple", "banana", "cherry"}  # Using curly braces
colors = set(["red", "green", "blue"])  # Using set() constructor

2. Unique Elements

Sets automatically enforce uniqueness. If you attempt to add a duplicate element, it will be ignored.

fruits = {"apple", "banana", "cherry", "apple"}  # "apple" is added only once
print(fruits)  # Output: {"apple", "banana", "cherry"}

3. Accessing Elements

Since sets are unordered, you cannot access elements by an index like in lists or tuples. Instead, you can check for membership using the in operator.

fruits = {"apple", "banana", "cherry"}
print("banana" in fruits)  # Output: True

4. Adding and Removing Elements

You can add elements to a set using the add() method and remove elements using the remove() method. If the element doesn’t exist in the set, remove() will raise an error, so it’s safer to use discard() to remove elements without errors.

fruits = {"apple", "banana", "cherry"}
fruits.add("orange")   # Add an element
fruits.remove("apple") # Remove an element
fruits.discard("kiwi") # Remove an element that may not exist

5. Set Operations

Sets support various set operations, including union (|), intersection (&), difference (-), and symmetric difference (^).

set1 = {1, 2, 3}
set2 = {3, 4, 5}

union_result = set1 | set2         # Union: {1, 2, 3, 4, 5}
intersection_result = set1 & set2  # Intersection: {3}
difference_result = set1 - set2    # Difference: {1, 2}
symmetric_diff_result = set1 ^ set2  # Symmetric Difference: {1, 2, 4, 5}

Boolean Type

Boolean Data Type in Python

The Boolean data type in Python is a fundamental data type that represents only two possible values: True and False. Booleans are used for making decisions, conditional statements, and logical operations. They are named after the mathematician George Boole, who developed Boolean algebra, a branch of algebra that deals with true/false values.

Here’s an explanation of the Boolean data type in Python with examples:

Boolean Data Type

Boolean values are often used to evaluate conditions and make decisions in Python. They serve as the basis for control flow in programs, allowing you to execute different code blocks depending on whether a condition is True or False.

Example 1: Using Booleans for Comparison

x = 5
y = 10

# Comparing values
is_greater = x > y  # False
is_equal = x == y  # False

print(is_greater)
print(is_equal)

In this example, we compare x and y, and the results (False) are assigned to the variables is_greater and is_equal. This demonstrates how Booleans are used in comparison operations.

Example 2: Using Booleans in Conditional Statements

temperature = 30

if temperature > 25:
    print("It's a hot day!")
else:
    print("It's not too hot.")

Here, we use a Boolean condition (temperature > 25) to determine which branch of the if statement to execute. If the condition is True, it prints “It’s a hot day!”; otherwise, it prints “It’s not too hot.”

Example 3: Using Booleans in Logical Operations

is_sunny = True
is_warm = False

# Logical AND operation
if is_sunny and is_warm:
    print("It's a sunny and warm day!")

# Logical OR operation
if is_sunny or is_warm:
    print("It's either sunny or warm (or both)!")

In this example, we perform logical AND and OR operations using Boolean variables is_sunny and is_warm. Depending on the combinations of True and False, different messages are printed.

Conclusion

Hope, now you understood python data types with examples, python data type list, how many data types in python, data types in python with examples, python data type list, mutable and immutable data types in python. keep learning , keep exploring…….

Hello Guys, Ayush this side. I am founder of studypunchx. I love to share trending and useful informations. keep Growing.....

Leave a Comment