Python Data Types Overview
In Python, every value has a datatype. Since Python is a dynamically typed language, you don’t need to declare the type of a variable explicitly; the interpreter infers the type at runtime based on the value assigned.
Understanding data types is the foundation of efficient programming. It determines how much memory is allocated, what operations can be performed, and how data is stored. This guide covers everything from basic scalars like integers to complex collections like dictionaries and sets.
1. Classification of Built-in Data Types
Python’s built-in data types can be broadly categorized into the following groups:
| Category | Types | Description |
|---|---|---|
| Numeric | int, float, complex | Used for mathematical calculations. |
| Sequence | str, list, tuple, range | Ordered collections of items. |
| Mapping | dict | Key-value pairs for fast lookups. |
| Set | set, frozenset | Unordered collections of unique items. |
| Boolean | bool | Logical values: True or False. |
| Binary | bytes, bytearray, memoryview | Handling binary data/files. |
| None | NoneType | Represents the absence of value. |
2. Numeric Data Types
Python supports three distinct numeric types. Notably, Python 3 'int' has arbitrary precision, meaning it can store numbers as large as your memory allows.
- int: Whole numbers (e.g., 10, -5, 1000000).
- float: Real numbers with decimal points (e.g., 3.14, -0.001, 2e4).
- complex: Numbers with real and imaginary parts (e.g., 3 + 5j).
a = 10 # int
b = 10.5 # float
c = 2 + 3j # complex
print(type(a)) # <class 'int'>
print(a + b) # 20.5 (implicit conversion to float)
print(c.real) # 2.0
3. Sequence Data Types
Sequences allow you to store multiple values in an organized, indexed manner.
Strings (str)
Strings are immutable sequences of Unicode characters. Once created, they cannot be changed in place.
msg = "Hello CodeCrown"
print(msg[0]) # 'H'
# msg[0] = 'h' # TypeError: strings are immutable
Lists (list)
Lists are the most versatile data structure. They are mutable (can be changed) and can hold different data types.
my_list = [1, "Python", 3.14]
my_list.append("New Item")
my_list[0] = 100 # Lists are mutable
print(my_list) # [100, 'Python', 3.14, 'New Item']
Tuples (tuple)
Tuples are like lists but immutable. They are faster than lists and are used to ensure data remains constant.
point = (10, 20)
# point[0] = 15 # Error! Tuples cannot be modified
4. Mapping (Dictionaries) and Set Types
Dictionaries (dict)
A dictionary is an unordered collection of data in a key:value pair form. It is highly optimized for retrieving data when the key is known.
user = {"name": "Alice", "age": 25, "role": "Developer"}
print(user["name"]) # Alice
user["age"] = 26 # Updating value
Sets (set)
A set is an unordered collection with no duplicate elements. It is useful for membership testing and mathematical operations like union or intersection.
numbers = {1, 2, 3, 3, 2}
print(numbers) # {1, 2, 3} (Duplicates removed)
5. Mutability: The Golden Rule
In Python, knowing whether a type is mutable or immutable is critical for avoiding bugs, especially when passing variables to functions.
| Type | Mutable? | Can be changed after creation? |
|---|---|---|
| int, float, bool | No | Immutable |
| str | No | Immutable |
| tuple | No | Immutable |
| list | Yes | Mutable |
| dict | Yes | Mutable |
| set | Yes | Mutable |
6. Type Conversion (Casting)
You can convert between types using constructor functions like int(), float(), str(), list(), and tuple().
x = "100"
y = int(x) # Convert string to int
z = float(y) # Convert int to float
my_tuple = (1, 2, 3)
my_list = list(my_tuple) # Convert tuple to list
Summary
Choosing the right data type is essential for writing clean, efficient Python code. Use lists for collections you need to modify, tuples for fixed data, dictionaries for associated data, and sets to handle unique items. Understanding these types will make learning advanced Python topics like Data Science or Web Development much easier.
Codecrown