Learn › Python Programming

Lists, Tuples & Dicts

Explore Python's core data structures including lists, tuples, dictionaries, and sets with practical manipulation techniques.

Lists

Lists are Python's most versatile data structure, providing ordered, mutable sequences that can hold elements of any type. They support indexing, slicing, and a rich set of methods for adding, removing, and sorting elements. Lists are implemented as dynamic arrays, making index access O(1) but insertion at the beginning O(n). Understanding list operations is fundamental to effective Python programming.

# Creating and manipulating lists
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
fruits.insert(1, "avocado")
print(fruits)  # ['apple', 'avocado', 'banana', 'cherry', 'date']

# Removing elements
fruits.remove("banana")
last = fruits.pop()
print(last)    # 'date'
print(fruits)  # ['apple', 'avocado', 'cherry']

# Sorting and reversing
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
print(numbers)  # [1, 1, 2, 3, 4, 5, 6, 9]

# List slicing
print(numbers[2:5])   # [2, 3, 4]
print(numbers[::2])   # [1, 2, 4, 6]
copy = numbers[:]     # shallow copy

Tuples

Tuples are immutable sequences that are often used to represent fixed collections of related values. Because they cannot be modified after creation, tuples are hashable and can be used as dictionary keys or set elements. They are slightly more memory-efficient than lists and communicate the intent that the data should not change. Tuple unpacking is a powerful feature that allows you to assign multiple variables in a single statement.

# Creating tuples
point = (3, 4)
rgb = (255, 128, 0)
singleton = (42,)  # Note the trailing comma

# Tuple unpacking
x, y = point
print(f"x={x}, y={y}")  # x=3, y=4

# Swapping values
a, b = 1, 2
a, b = b, a
print(a, b)  # 2, 1

# Named tuples for readability
from collections import namedtuple

Person = namedtuple("Person", ["name", "age", "city"])
alice = Person("Alice", 30, "NYC")
print(alice.name)   # "Alice"
print(alice.age)    # 30
print(alice._asdict())  # {'name': 'Alice', 'age': 30, 'city': 'NYC'}

Dictionaries

Dictionaries are key-value mappings that provide O(1) average-time lookups, insertions, and deletions. Keys must be hashable and unique, while values can be any Python object. Since Python 3.7, dictionaries maintain insertion order as part of the language specification. The get() method provides a safe way to access values with a default fallback when a key might not exist.

# Creating and accessing dictionaries
student = {
    "name": "Alice",
    "age": 22,
    "grades": [88, 92, 79, 95]
}

print(student["name"])           # "Alice"
print(student.get("email", "N/A"))  # "N/A"

# Modifying dictionaries
student["email"] = "alice@example.com"
student.update({"age": 23, "major": "CS"})

# Iterating over dictionaries
for key, value in student.items():
    print(f"{key}: {value}")

# Dictionary methods
keys = list(student.keys())
values = list(student.values())
popped = student.pop("email")

# Merging dictionaries (Python 3.9+)
defaults = {"theme": "dark", "lang": "en"}
overrides = {"lang": "fr", "font_size": 14}
config = defaults | overrides
print(config)  # {'theme': 'dark', 'lang': 'fr', 'font_size': 14}

Sets and Comprehensions

Sets are unordered collections of unique elements that support mathematical set operations like union, intersection, and difference. They are ideal for removing duplicates, membership testing, and comparing groups of items. Sets require their elements to be hashable, so you cannot store lists or dictionaries in a set. Frozensets are immutable versions of sets that can themselves be stored in other sets or used as dictionary keys.

# Creating sets
colors = {"red", "green", "blue"}
numbers = set([1, 2, 2, 3, 3, 3])
print(numbers)  # {1, 2, 3}

# Set operations
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}

print(a | b)    # Union: {1, 2, 3, 4, 5, 6, 7, 8}
print(a & b)    # Intersection: {4, 5}
print(a - b)    # Difference: {1, 2, 3}
print(a ^ b)    # Symmetric difference: {1, 2, 3, 6, 7, 8}

# Membership testing (O(1) average)
print(3 in a)   # True

# Set comprehension
sentence = "hello world hello python world"
unique_words = {word for word in sentence.split()}
print(unique_words)  # {'hello', 'world', 'python'}

# Frozenset
fs = frozenset([1, 2, 3])
nested_sets = {fs, frozenset([4, 5])}

← Functions & Scope · Object-Oriented Programming →