Python Data Structures
Data structures are fundamental to programming, providing ways to organize and manipulate data efficiently. Python offers a rich set of built-in data structures and also supports more advanced structures through libraries. These tools make Python versatile for everything from simple scripts to complex applications. GeeksForGeeks Real Python
🌍 Built-in Data Structures
Lists
- Ordered, mutable collections.
- Can store heterogeneous data types.
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # ["apple", "banana", "cherry", "orange"]
Tuples
- Ordered, immutable collections.
- Useful for fixed data sets.
coordinates = (10, 20)
print(coordinates[0]) # 10
Sets
- Unordered collections of unique elements.
- Efficient for membership tests.
unique_numbers = {1, 2, 3, 3}
print(unique_numbers) # {1, 2, 3}
Dictionaries
- Key-value pairs, similar to hash maps.
- Fast lookups and updates.
student = {"name": "Alice", "age": 22}
student["grade"] = "A"
🔄 Advanced Data Structures
Python’s collections module and other libraries extend functionality:
- OrderedDict: Maintains insertion order of keys.
- defaultdict: Provides default values for missing keys.
- ChainMap: Combines multiple dictionaries into one view.
- NamedTuple: Immutable, lightweight object-like tuples.
- Deque: Double-ended queue for fast appends/pops from both ends. Real Python
✨ Strings as Data Structures
Strings in Python behave like immutable sequences of Unicode characters.
text = "Python"
print(text[0]) # P
print(text[::-1]) # nohtyP
📊 Comparison Table
| Data Structure | Ordered | Mutable | Unique Elements | Typical Use Case |
|---|---|---|---|---|
| List | Yes | Yes | No | General-purpose collection |
| Tuple | Yes | No | No | Fixed data sets |
| Set | No | Yes | Yes | Membership tests, deduplication |
| Dictionary | Keys unordered (pre-3.7), ordered (3.7+) | Yes | Keys unique | Fast lookups, mappings |
📖 Conclusion
Python’s data structures—lists, tuples, sets, and dictionaries—form the foundation of everyday programming. With advanced structures like OrderedDict, defaultdict, and deque, Python provides flexibility for specialized needs. Mastering these tools allows developers to write efficient, clean, and scalable code.
No comments:
Post a Comment