Data Structures
Python’s built-in data structures are incredibly powerful. Unlike C++ or Java where you might need to import special libraries for hash maps or dynamic arrays, Python has them built into the core language syntax.1. Lists (Dynamic Arrays)
Alist is an ordered, mutable sequence of items. It can hold mixed types (integers, strings, other lists).
Slicing [start:end:step]
Slicing allows you to extract sub-parts of a list. It creates a new list.
List Comprehensions
This is a “Pythonic” way to create lists based on existing lists. It’s often more readable and faster than a for-loop.2. Dictionaries (Hash Maps)
Adict stores Key-Value pairs. Keys must be immutable (strings, numbers, tuples) and unique. Lookups are extremely fast (O(1)).
Dict Comprehensions
Just like lists, you can build dictionaries dynamically.3. Sets (Unique Collection)
Aset is an unordered collection of unique elements. It is implemented as a hash table without values.
Use Cases: Removing duplicates, membership testing, and mathematical set operations.
4. Tuples (Immutable Lists)
Atuple is like a list, but it cannot be changed (immutable).
Why use tuples?
- Safety: Guarantees data hasn’t changed.
- Performance: Slightly faster than lists.
- Hashable: Can be used as dictionary keys (lists cannot).
5. The collections Module
The standard library collections module provides specialized data structures that go beyond the basics.
Counter
A dictionary subclass for counting hashable objects.
defaultdict
A dictionary that provides a default value for missing keys. This avoids KeyError and manual checks.
Summary
- Lists: Ordered, mutable. Use for sequences of data.
- Dicts: Key-Value. Use for lookups and structured data.
- Sets: Unique. Use for math and deduplication.
- Tuples: Immutable. Use for fixed records.
- Comprehensions: The concise way to build lists and dicts.