Chapter 7 of 12
Lists are Python's most versatile data structure โ ordered, mutable collections that can hold any type of value. They have a rich set of built-in methods and support for list comprehensions, which are one of Python's most elegant features.
# Creating lists
courses = ["HTML", "CSS", "JavaScript", "Python"]
numbers = [1, 2, 3, 4, 5]
mixed = [42, "hello", True, None, [1, 2]] # mixed types (avoid)
# Accessing elements โ zero-indexed
courses[0] # "HTML"
courses[-1] # "Python" (last item)
courses[-2] # "JavaScript" (second to last)
# Slicing โ courses[start:stop:step]
courses[1:3] # ["CSS", "JavaScript"]
courses[:2] # ["HTML", "CSS"]
courses[2:] # ["JavaScript", "Python"]
courses[::-1] # ["Python", "JavaScript", "CSS", "HTML"] (reversed)
# Mutating methods
courses.append("Django") # add to end
courses.insert(1, "React") # insert at index 1
courses.extend(["Flask", "FastAPI"]) # add multiple items
removed = courses.pop() # remove and return last
removed = courses.pop(0) # remove and return by index
courses.remove("React") # remove first matching value
courses.sort() # sort in place
courses.reverse() # reverse in place
# Non-mutating operations
len(courses) # number of items
"Python" in courses # True/False
courses.count("CSS") # how many times it appears
courses.index("CSS") # index of first matchnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Instead of:
squares = []
for n in numbers:
squares.append(n ** 2)
# Write:
squares = [n ** 2 for n in numbers]
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# With a condition
evens = [n for n in numbers if n % 2 == 0]
# [2, 4, 6, 8, 10]
# Transform and filter together
even_squares = [n ** 2 for n in numbers if n % 2 == 0]
# [4, 16, 36, 64, 100]
# Nested comprehensions
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [val for row in matrix for val in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]