Notes – Python Data Types
Data types in Python define the kind of data a variable can hold. Since Python is dynamically typed, you donโt need to specify data types explicitlyโPython detects them automatically.
1. Numeric Data Types
These are used to store numbers.
| Data Type | Description | Example |
|---|---|---|
| int | Integer (whole numbers) | x = 10 |
| float | Decimal numbers | y = 3.14 |
| complex | Complex numbers | z = 2 + 3j |
Example:
x = 10 # Integer
y = 3.14 # Float
z = 2 + 3j # Complex
print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'float'>
print(type(z)) # Output: <class 'complex'>
2. Sequence Data Types
These store ordered collections of data.
| Data Type | Description | Example |
|---|---|---|
| str | String (text) | "Hello, Python!" |
| list | Ordered, mutable collection | [1, 2, 3, "apple"] |
| tuple | Ordered, immutable collection | (10, 20, "banana") |
Example:
text = "Python" # String
numbers = [1, 2, 3] # List
coordinates = (4, 5) # Tuple
print(type(text)) # Output: <class 'str'>
print(type(numbers)) # Output: <class 'list'>
print(type(coordinates)) # Output: <class 'tuple'>
3. Set Data Types
Used to store unique, unordered collections.
| Data Type | Description | Example |
|---|---|---|
| set | Unordered, unique elements | {1, 2, 3, 3, 4} |
| frozenset | Immutable set | frozenset({1, 2, 3}) |
Example:
my_set = {1, 2, 3, 3, 4} # Duplicates removed
f_set = frozenset(my_set) # Immutable set
print(my_set) # Output: {1, 2, 3, 4}
print(type(f_set)) # Output: <class 'frozenset'>
4. Mapping Data Type
Stores key-value pairs.
| Data Type | Description | Example |
|---|---|---|
| dict | Stores key-value pairs | {"name": "John", "age": 25} |
Example:
student = {"name": "Alice", "age": 21, "course": "Python"}
print(student["name"]) # Output: Alice
5. Boolean Data Type
Represents True or False values.
| Data Type | Description | Example |
|---|---|---|
| bool | True or False values | is_active = True |
Example:
is_python_easy = True
print(type(is_python_easy)) # Output: <class 'bool'>
6. Binary Data Types
Used to handle binary data like images or files.
| Data Type | Description | Example |
|---|---|---|
| bytes | Immutable byte sequences | b"Hello" |
| bytearray | Mutable byte sequences | bytearray(5) |
| memoryview | View memory of an object | memoryview(b"Hello") |
Example:
b = bytes([65, 66, 67])
print(b) # Output: b'ABC'
ba = bytearray([65, 66, 67])
ba[0] = 97
print(ba) # Output: bytearray(b'aBC')
mv = memoryview(b"Hello")
print(mv[0]) # Output: 72 (ASCII value of 'H')
