Python Data Types 📊
Everything is an Object
In Python, every value is an object. Data types are actually classes and variables are instances (objects) of these classes. Understanding data types is crucial for performing operations without errors.
🎯 Real-World Application: Choosing the Right Type
📝 Strings (str)
Usernames, emails, text content.
🔢 Integers (int)
Age, count of items, ID numbers.
📋 Lists (list)
Shopping cart items, todo list (ordered, changeable).
🔐 Tuples (tuple)
GPS coordinates (lat, long), RGB colors (fixed, unchangeable).
📖 Dictionaries (dict)
User profiles (key: value), configuration settings.
🚫 Sets (set)
Storing unique IDs, finding common friends (no duplicates).
📋 Standard Data Types
| Category | Types | Mutable? |
|---|---|---|
| Text Type | str | No (Immutable) |
| Numeric Types | int, float, complex | No (Immutable) |
| Sequence Types | list, range | Yes (Mutable) / No |
| Sequence Types | tuple | No (Immutable) |
| Mapping Type | dict | Yes (Mutable) |
| Set Types | set | Yes (Mutable) |
| Set Types | frozenset | No (Immutable) |
| Boolean Type | bool | No (Immutable) |
🔍 Checking Data Types
You can use type() to check the class of an object, but isinstance() is often better because it checks for inheritance.
x = 5
print(type(x)) # Output: <class 'int'>
print(isinstance(x, int)) # Output: True🔄 Mutable vs Immutable
Understanding mutability is key to avoiding bugs.
🔒 Immutable
Cannot be changed after creation. If you modify it, Python creates a new object.
- int, float, bool, str, tuple, frozenset
🔓 Mutable
Can be changed in place. The memory address remains the same.
- list, dict, set
✨ Setting Specific Data Types
You can force a specific data type using constructor functions:
x = str("Hello World") # String
x = int(20) # Integer
x = float(20.5) # Float
x = complex(1j) # Complex
x = list(("apple", "banana")) # List
x = tuple(("apple", "banana")) # Tuple
x = range(6) # Range
x = dict(name="John", age=36) # Dict
x = set(("apple", "banana")) # Set
x = bool(5) # Boolean (True)💡 Did You Know?
Python has a special type called NoneType with a single value None. It is used to define a null value, or no value at all. It is not the same as 0, False, or an empty string.
x = None
print(type(x)) # <class 'NoneType'>