Python Data Types¶
- Python is a dynamically-typed language, which means you don’t need to declare the type of a variable explicitly. Python automatically assigns the type based on the value.
- You can check the type of any variable using:
type(variable)
Built-in Data Types¶
- Here are some of the most commonly used data types in Python:
| Type | Name |
|---|---|
| Text Type | str |
| Numeric Types | int, float, complex |
| Sequence Types | list, tuple, range |
| Mapping Type | dict |
| Set Types | set, frozenset |
| Boolean Type | bool |
| Binary Types | bytes, bytearray, memoryview |
| None Type | NoneType |
Text Type(String)¶
- What it is: Stores text or characters.
- Use case: When dealing with words, sentences, or any text-based information.
Real-life examples:
- A person’s name: "Raj"
- A social media post: "Learning Python is fun!"
# String example
name = "Alice"
message = "Learning Python is fun!"
print(name, type(name)) # Output: Alice <class 'str'>
print(message, type(message)) # Output: Learning Python is fun! <class 'str'>
Alice <class 'str'> Learning Python is fun! <class 'str'>
Numeric Types (int, float, complex)¶
Integer(int) – Whole numbers.
- Use case: Counting objects.
- Example: Number of students in a class: 25
Float(float) – Decimal numbers.
- Use case: Measurements and precise calculations.
- Example: Temperature: 36.6°C, Product price: $19.99
Complex (complex) – Numbers with real and imaginary parts.
- Use case: Scientific calculations, engineering problems.
- Example: Electrical impedance: 5 + 2j
# Integer
age = 25
print(age, type(age)) # Output: 25 <class 'int'>
# Float
temperature = 36.6
print(temperature, type(temperature)) # Output: 36.6 <class 'float'>
# Complex
z = 5 + 2j
print(z, type(z)) # Output: (5+2j) <class 'complex'>
25 <class 'int'> 36.6 <class 'float'> (5+2j) <class 'complex'>
Sequence Types(list, tuple, range)¶
List – Ordered collection that can be changed.
- Use case: Items that can be updated, like a shopping list.
- Example: ["apple", "banana", "orange"]
Tuple – Ordered collection that cannot be changed.
- Use case: Fixed data that should remain constant.
- Example: GPS coordinates: (28.6139, 77.2090)
Range – Represents a sequence of numbers.
- Use case: Iterating over numbers in a loop.
- Example: Days of the week numbered 0 to 6
# List
fruits = ["apple", "banana", "orange"]
print(fruits, type(fruits)) # Output: ['apple', 'banana', 'orange'] <class 'list'>
# Tuple
coordinates = (28.6139, 77.2090)
print(coordinates, type(coordinates)) # Output: (28.6139, 77.2090) <class 'tuple'>
# Range
days = range(7)
print(list(days), type(days)) # Output: [0, 1, 2, 3, 4, 5, 6] <class 'range'>
['apple', 'banana', 'orange'] <class 'list'> (28.6139, 77.209) <class 'tuple'> [0, 1, 2, 3, 4, 5, 6] <class 'range'>
Mapping Type(dict)¶
- What it is: Stores data as key-value pairs.
- Use case: When you want to associate one piece of information with another.
Real-life example:
- Person’s profile: { "name": "Raj", "age": 30, "city": "Delhi" }
person = {"name": "Raj", "age": 30, "city": "Delhi"}
print(person, type(person)) # Output: {'name': 'Raj', 'age': 30, 'city': 'Delhi'} <class 'dict'>
{'name': 'Raj', 'age': 30, 'city': 'Delhi'} <class 'dict'>
Set Types(set, frozenset)¶
Set – Collection of unique, unordered items.
- Use case: Removing duplicates, keeping a list of unique things.
- Example: Unique words in a book.
Frozenset – Immutable version of a set.
- Use case: Data that should not change.
- Example: Allowed commands in an application.
# Set
unique_items = {"train", "bus", "bike"}
print(unique_items, type(unique_items)) # Output: {'bike', 'bus', 'train'} <class 'set'>
# Frozenset
frozen_items = frozenset({"train", "bus", "bike"})
print(frozen_items, type(frozen_items)) # Output: frozenset({'bike', 'bus', 'train'}) <class 'frozenset'>
{'train', 'bike', 'bus'} <class 'set'>
frozenset({'bus', 'bike', 'train'}) <class 'frozenset'>
Boolean Type(bool)¶
- What it is: Stores either True or False.
- Use case: Decision making, logical conditions.
Real-life examples:
- Is a user logged in? True or False
- Is a password correct? True or False
is_logged_in = True
has_access = False
print(is_logged_in, type(is_logged_in)) # Output: True <class 'bool'>
print(has_access, type(has_access)) # Output: False <class 'bool'>
True <class 'bool'> False <class 'bool'>
Binary Types(bytes, bytearray, memoryview)¶
- What it is: Stores data in binary format.
- Use case: Handling files, images, audio, or network communication.
Real-life example:
- Storing a photo or sending a file over the internet.
# Bytes
data_bytes = b"Hello"
print(data_bytes, type(data_bytes)) # Output: b'Hello' <class 'bytes'>
# Bytearray
data_array = bytearray(5) # Array of 5 zeroed bytes
print(data_array, type(data_array)) # Output: bytearray(b'\x00\x00\x00\x00\x00') <class 'bytearray'>
# Memoryview
data_view = memoryview(bytes(5))
print(data_view, type(data_view)) # Output: <memory at 0x...> <class 'memoryview'>
b'Hello' <class 'bytes'> bytearray(b'\x00\x00\x00\x00\x00') <class 'bytearray'> <memory at 0x78eabd97cb80> <class 'memoryview'>
None Type(NoneType)¶
- What it is: Represents absence of value.
- Use case: Placeholder for missing or unknown data.
Real-life examples:
- A student hasn’t submitted homework: None
- A variable waiting to be assigned a value.
nothing = None
print(nothing, type(nothing)) # Output: None <class 'NoneType'>
None <class 'NoneType'>
Python Type Casting¶
- There may be times when you want to convert one type of variable to another type variable. This can be done with type casting.
- Python supports two main types of type casting:
- Implicit Casting (Type Conversion)
- Explicit Casting (Type Conversion)
1. Implicit Casting¶
Definition: The Python interpreter automatically converts a smaller data type to a larger data type without user intervention.
Purpose: To prevent data loss during operations.
Rules: Implicit casting usually happens in expressions involving mixed data types, where Python promotes the smaller type to a larger type.
# Implicit Type Conversion Example
int_var = 10 # Integer
float_var = 3.5 # Float
# Adding integer and float
result = int_var + float_var
print(result) # Output: 13.5
print(type(result)) # Output: <class 'float'>
13.5 <class 'float'>
Explanation:
- Here,
int_varis implicitly converted to a float before the addition because Python promotes the smaller type (integer) to the larger type (float) to avoid data loss.
2. Explicit Casting¶
Definition: The programmer explicitly converts a value from one type to another using built-in functions such as int(), float(), str(), etc.
Purpose: Provides control over the type conversion.
You can convert one data type to another using constructors or type casting functions like int(), float(), str(), list(), etc.
In type casting, there is a risk of data loss when we force a value to be converted to a specific data type.
Why we need it:
Sometimes your data isn’t in the format you want. For example:
- You read a number from a user as a string ("25") but need it as an integer for calculations.
- You want to store numbers in a list or convert a list to a tuple for safety.
Text Type (String)¶
- Strings are text data. You can convert numbers or other types to strings.
# Example: converting a number to a string
age = 25
age_str = str(age) # convert integer to string
print("Age as string:", age_str)
print("Data type:", type(age_str))
Age as string: 25 Data type: <class 'str'>
Numeric Types:¶
Integer
# Example: converting a float to integer
price = 49.99
price_int = int(price) # removes decimal part
print("Price as integer:", price_int)
print("Data type:", type(price_int))
Price as integer: 49 Data type: <class 'int'>
Float
# Example: converting an integer to float
quantity = 5
quantity_float = float(quantity) # adds decimal point
print("Quantity as float:", quantity_float)
print("Data type:", type(quantity_float))
Quantity as float: 5.0 Data type: <class 'float'>
Complex Number
# Example: making a complex number
a = complex(3, 4) # 3 + 4j
print("Complex number:", a)
print("Data type:", type(a))
Complex number: (3+4j) Data type: <class 'complex'>
Sequence Types¶
List
# Example: creating a list of vehicles
vehicles = list(["car", "bike", "bus"])
print("List:", vehicles)
print("Data type:", type(vehicles))
List: ['car', 'bike', 'bus'] Data type: <class 'list'>
Tuple
# Example: converting list to tuple
vehicles_tuple = tuple(vehicles)
print("Tuple:", vehicles_tuple)
print("Data type:", type(vehicles_tuple))
Tuple: ('car', 'bike', 'bus')
Data type: <class 'tuple'>
Range
# Example: creating a range of numbers
numbers = range(5) # 0,1,2,3,4
print("Range:", list(numbers)) # convert to list to see numbers
print("Data type:", type(numbers))
Range: [0, 1, 2, 3, 4] Data type: <class 'range'>
Mapping Type(dict)¶
# Example: creating a dictionary
person = dict(name="Raj", age=30)
print("Dictionary:", person)
print("Data type:", type(person))
Dictionary: {'name': 'Raj', 'age': 30}
Data type: <class 'dict'>
Set Types¶
Set
# Example: storing unique items
fruits = set(["apple", "banana", "apple", "orange"])
print("Set:", fruits) # duplicates removed automatically
print("Data type:", type(fruits))
Set: {'orange', 'banana', 'apple'}
Data type: <class 'set'>
Frozenset
# Example: immutable set
frozen_fruits = frozenset(fruits)
print("Frozenset:", frozen_fruits)
print("Data type:", type(frozen_fruits))
Frozenset: frozenset({'orange', 'banana', 'apple'})
Data type: <class 'frozenset'>
Boolean Type¶
# Example: converting numbers to boolean
value = 0
is_true = bool(value) # 0 = False, any other number = True
print("Boolean value:", is_true)
print("Data type:", type(is_true))
Boolean value: False Data type: <class 'bool'>
Binary Types¶
Bytes
data = bytes(10)
print("Bytes:", data)
print("Data type:", type(data))
Bytes: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' Data type: <class 'bytes'>
Bytearray
data_array = bytearray(10)
print("Bytearray:", data_array)
print("Data type:", type(data_array))
Bytearray: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') Data type: <class 'bytearray'>
Memoryview
mem = memoryview(bytes(5))
print("Memoryview:", mem)
print("Data type:", type(mem))
Memoryview: <memory at 0x78eab4e8d180> Data type: <class 'memoryview'>