Chapter 3 Summary

Learn about collections in Python.

Ali Berro

By Ali Berro

5 min read Section
From: Python Fundamentals: From Zero to Hero

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: in and not 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 lists
fruits = ["apple", "banana", "orange"]
fruits.append("grape") # Add element
fruits.remove("banana") # Remove element
print(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 keys
x, y = (10, 20) # Unpacking
point = (10, 20)
locations = {point: "origin"} # Can be used as dictionary key
print(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 formatting
text = "Hello World"
print(text.upper()) # "HELLO WORLD"
print(text.split()) # ["Hello", "World"]
name = "Alice"
age = 25
msg = 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 operations
student_grades = {"Alice": 95, "Bob": 87, "Charlie": 92}
print(student_grades["Alice"]) # 95 (fast lookup)
student_grades["David"] = 90 # Add new entry
for 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 operations
set1 = {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: True

Frozen 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 keys
edges = {
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): Returns True if any element is truthy
  • all(iterable): Returns True if all elements are truthy
  • hash(obj): Returns hash value of hashable objects
  • divmod(a, b): Returns (quotient, remainder) tuple
  • bin(n), oct(n), hex(n): Convert integers to different number bases
  • zip(*iterables): Combines multiple iterables into tuples
  • enumerate(iterable): Adds indices, returns (index, value) pairs
  • reversed(seq): Returns reverse iterator
  • slice(start, stop, step): Creates slice objects for reusable slicing
# Example: Using built-in functions
numbers = [1, 2, 3, 4, 5]
print(any([0, 1, 0])) # True
print(all([1, 2, 3])) # True
print(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

CollectionMutableOrderedIndexedHashableDuplicatesUse Case
ListYesYesYesNoYesDynamic ordered collections
TupleNoYesYesYesYesFixed ordered collections
StringNoYesYesYesYesText data
DictionaryYesYes*By keyNoKeys: NoKey-value mappings
SetYesNoNoNoNoUnique items, set operations
Frozen SetNoNoNoYesNoImmutable unique items

*Dictionaries maintain insertion order in Python 3.7+

Course Progress

Section 29 of 61

Back to Course