Python Data Types
Fundamental Data Types
Python provides several built-in data types grouped into categories:
- **Numeric**: `int`, `float`, `complex`
- **Sequence**: `str`, `list`, `tuple`, `range`
- **Mapping**: `dict`
- **Set**: `set`, `frozenset`
- **Boolean**: `bool`
- **Binary**: `bytes`, `bytearray`, `memoryview`
ℹ️ Note: Use the built-in `type()` function to check the data type of any variable.
Numeric Types
⚠️ Warning: Floating-point numbers are imprecise for exact arithmetic. Use the `decimal` or `fractions` module for precise calculations.
Example
# Integers (arbitrary precision)
x = 42
y = -9876543210
# Floating-point numbers
pi = 3.14159
sci = 6.022e23 # Scientific notation
# Complex numbers
z = 3 + 5j
print(z.real, z.imag) # 3.0 5.0
Output
3.0 5.0
Sequence Types Comparison
Type | Mutable? | Syntax | Typical Use Case |
---|---|---|---|
String | Immutable | `"text"` | Store and manipulate text |
List | Mutable | `[1, 2, 3]` | Ordered collection of items |
Tuple | Immutable | `(1, 2, 3)` | Fixed collection of items |
Range | Immutable | `range(5)` | Efficient sequences of integers |
Dictionaries & Sets
Example
# Dictionary (key-value pairs)
user = {
"name": "Alice",
"age": 30,
"is_active": True
}
# Set (unique elements, mutable)
primes = {2, 3, 5, 7}
primes.add(11)
# Frozenset (immutable set)
constants = frozenset({3.14, 2.718})
ℹ️ Note: Dictionary keys must be immutable (e.g., strings, numbers, or tuples).
Type Conversion
⚠️ Warning: Invalid conversions (e.g., `int("abc")`) raise `ValueError`.
Example
# Explicit conversion
num_str = "123"
num_int = int(num_str)
num_float = float(num_str)
# Implicit conversion (type coercion)
result = 3 + 5.0 # int + float → float
print(type(result))
Output
<class 'float'>
Special Cases
Some built-in types represent special situations:
Example
# None type
x = None # Represents 'no value' or 'null'
# Ellipsis object
placeholder = ... # Commonly used in slicing or as a stub
# Boolean truthiness
print(bool(0)) # False
print(bool("Hi")) # True
print(bool([])) # False
Output
False True False
Exercises
- Create variables for all fundamental types and print their types using `type()`
- Convert between `str`, `int`, and `float` safely with error handling
- Show how `list` can be modified while `tuple` cannot
- Use `None` in a conditional statement to check for missing values