Summary
This chapter introduced Python’s collection types and essential built-in functions for working with data structures. Collections are fundamental data types that allow you to store and organize multiple values efficiently.
Key Concepts
Mutability vs. Immutability
- Mutable types (lists, dictionaries, sets) can be modified after creation
- Immutable types (tuples, strings, frozen sets) cannot be modified after creation
Hashability
- Hashable objects can be used as dictionary keys and set elements
- Only immutable types are hashable (strings, numbers, tuples, frozen sets)
- Mutable types (lists, dictionaries, sets) are not hashable
Ordering
- Ordered collections (lists, tuples, strings) maintain element order and support indexing
- Unordered collections (sets, frozen sets) don’t guarantee order
- Dictionaries maintain insertion order (Python 3.7+)
Common Sequence Operations
All sequences (lists, tuples, strings) support:
- Indexing:
seq[index] - Slicing:
seq[start:stop:step] - Membership:
inandnot in - Length:
len(seq) - Concatenation:
+ - Repetition:
* - Built-in functions:
min(),max(),sum(),count(),index()
Collection Types
Lists
Lists are mutable, ordered sequences that can store elements of any type. They support indexing, slicing, and various methods for adding, removing, and modifying elements.
# Example: Working with listsfruits = ["apple", "banana", "orange"]fruits.append("grape") # Add elementfruits.remove("banana") # Remove elementprint(fruits[0]) # Access by index: "apple"print(fruits[1:3]) # Slice: ["orange", "grape"]Tuples
Tuples are immutable, ordered sequences. Once created, they cannot be modified, making them hashable and suitable as dictionary keys. They support tuple packing and unpacking.
# Example: Tuple unpacking and using as dictionary keysx, y = (10, 20) # Unpackingpoint = (10, 20)locations = {point: "origin"} # Can be used as dictionary keyprint(locations[(10, 20)]) # "origin"Strings
Strings are immutable sequences of characters. They support all sequence operations plus specialized text manipulation methods and formatting.
# Example: String operations and formattingtext = "Hello World"print(text.upper()) # "HELLO WORLD"print(text.split()) # ["Hello", "World"]name = "Alice"age = 25msg = f"My name is {name} and I am {age} years old"Dictionaries
Dictionaries are mutable collections of key-value pairs. Keys must be immutable and hashable, while values can be of any type. They provide fast lookups by key.
# Example: Dictionary operationsstudent_grades = {"Alice": 95, "Bob": 87, "Charlie": 92}print(student_grades["Alice"]) # 95 (fast lookup)student_grades["David"] = 90 # Add new entryfor name, grade in student_grades.items(): print(f"{name}: {grade}")Sets
Sets are mutable, unordered collections of unique elements. All elements must be immutable and hashable. They excel at membership testing and mathematical set operations.
# Example: Set operationsset1 = {1, 2, 3, 4}set2 = {3, 4, 5, 6}print(set1 & set2) # Intersection: {3, 4}print(set1 | set2) # Union: {1, 2, 3, 4, 5, 6}print(3 in set1) # Membership test: TrueFrozen Sets
Frozen Sets are immutable versions of sets. Since they cannot be modified after creation, they are hashable and can be used as dictionary keys or as elements in other sets.
# Example: Using frozen sets as dictionary keysedges = { frozenset([1, 2]): "edge_1_2", frozenset([2, 3]): "edge_2_3"}print(edges[frozenset([1, 2])]) # "edge_1_2"Built-in Functions
Python provides powerful built-in functions for working with collections:
any(iterable): ReturnsTrueif any element is truthyall(iterable): ReturnsTrueif all elements are truthyhash(obj): Returns hash value of hashable objectsdivmod(a, b): Returns(quotient, remainder)tuplebin(n),oct(n),hex(n): Convert integers to different number baseszip(*iterables): Combines multiple iterables into tuplesenumerate(iterable): Adds indices, returns(index, value)pairsreversed(seq): Returns reverse iteratorslice(start, stop, step): Creates slice objects for reusable slicing
# Example: Using built-in functionsnumbers = [1, 2, 3, 4, 5]print(any([0, 1, 0])) # Trueprint(all([1, 2, 3])) # Trueprint(list(zip([1, 2], ['a', 'b']))) # [(1, 'a'), (2, 'b')]for i, num in enumerate(numbers): print(f"{i}: {num}") # 0: 1, 1: 2, ...Quick Reference
| Collection | Mutable | Ordered | Indexed | Hashable | Duplicates | Use Case |
|---|---|---|---|---|---|---|
| List | Yes | Yes | Yes | No | Yes | Dynamic ordered collections |
| Tuple | No | Yes | Yes | Yes | Yes | Fixed ordered collections |
| String | No | Yes | Yes | Yes | Yes | Text data |
| Dictionary | Yes | Yes* | By key | No | Keys: No | Key-value mappings |
| Set | Yes | No | No | No | No | Unique items, set operations |
| Frozen Set | No | No | No | Yes | No | Immutable unique items |
*Dictionaries maintain insertion order in Python 3.7+
