Python Data Collections
Learn about the data collection types in Python, including list, tuple, set, and dict.
Last updated: 2024-12-12Python provides several data collection types that allow storing multiple elements within a single structure. These structures are designed for various tasks and make the code more convenient.
Types of Data Collections
Python includes the following primary data collection types:
- list
- tuple
- set
- dict
1. list
The list
type is used to store ordered, mutable, and duplicate elements.
Features:
- Ordered.
- Elements can be modified, added, or removed.
- Supports various data types.
Examples:
fruits = ["apple", "banana", "cherry"]
colors = ["red", "green", "blue"]
numbers = [1, 2, 3, 4, 5]
Useful Methods:
fruits.append("pear") # Add element
fruits.remove("banana") # Remove element
fruits.sort() # Sort list
print(len(fruits)) # Get length
2. tuple
The tuple
type is used to store ordered, immutable elements.
Features:
- Ordered.
- Elements cannot be modified.
- Supports various data types.
Examples:
coordinates = (10.5, 25.4)
categories = ("book", "movie", "music")
Basic Operations:
print(coordinates[0]) # Access first element
print(len(categories)) # Get length
3. set
The set
type is used to store unordered, unique elements.
Features:
- Elements must be unique.
- Unordered.
- Supports mathematical operations.
Examples:
numbers = {1, 2, 3, 4, 5}
names = {"Ali", "Vali", "Sami"}
Useful Operations:
numbers.add(6) # Add element
numbers.remove(2) # Remove element
union_set = numbers.union({7, 8}) # Union
intersection_set = numbers.intersection({3, 4, 5}) # Intersection
4. dict
The dict
type stores key-value pairs.
Features:
- Ordered (Python 3.7+).
- Keys must be unique.
- Keys must be immutable types (
int
,str
,tuple
).
Examples:
student = {
"name": "Ali",
"age": 20,
"year": 2
}
Useful Methods:
print(student["name"]) # Access value
student["year"] = 3 # Modify value
student["faculty"] = "IT" # Add new key-value pair
print(student.keys()) # List of keys
print(student.values()) # List of values
Specialized Data Collections (Collections Module)
Python's collections
module provides specialized data structures for managing collections. Some of them are:
namedtuple
— Creates named structures.deque
— Optimized list for adding/removing items from both ends.ChainMap
— Combines multiple dictionaries into a single view.Counter
— Special dictionary for counting elements.OrderedDict
— Keeps insertion order.defaultdict
— Returns default values for missing keys.UserDict
,UserList
,UserString
— Extend dictionary, list, and string objects.
Conclusion
Data collections are essential in Python programming, each designed for specific tasks. Using them properly enhances program efficiency and code clarity.