Lists
Lists are mutable, ordered sequences of any type.
# Creating lists
empty = []
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True, None]
nested = [[1, 2], [3, 4], [5, 6]]
# From iterables
chars = list("Python") # ['P', 'y', 't', 'h', 'o', 'n']
nums = list(range(5)) # [0, 1, 2, 3, 4]
Indexing and Slicing
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
# Indexing (0-based)
print(fruits[0]) # apple
print(fruits[-1]) # elderberry (last)
print(fruits[-2]) # date
# Slicing [start:stop:step]
print(fruits[1:3]) # ['banana', 'cherry']
print(fruits[:3]) # ['apple', 'banana', 'cherry']
print(fruits[2:]) # ['cherry', 'date', 'elderberry']
print(fruits[::2]) # ['apple', 'cherry', 'elderberry']
print(fruits[::-1]) # reversed list
List Methods
lst = [3, 1, 4, 1, 5, 9]
lst.append(2) # add to end: [3,1,4,1,5,9,2]
lst.insert(0, 0) # insert at index: [0,3,1,4,1,5,9,2]
lst.extend([6, 5, 3]) # extend: adds multiple items
lst.remove(1) # removes first occurrence of 1
popped = lst.pop() # removes and returns last
popped = lst.pop(0) # removes and returns item at index 0
lst.sort() # sort in place
lst.sort(reverse=True) # descending
lst.reverse() # reverse in place
lst.clear() # remove all items
nums = [3, 1, 4, 1, 5]
print(nums.count(1)) # 2 โ count occurrences
print(nums.index(4)) # 2 โ index of first occurrence
print(len(nums)) # 5
List Copying
original = [1, 2, 3]
# Shallow copy methods:
copy1 = original.copy()
copy2 = original[:]
copy3 = list(original)
# Modifying copy doesn't affect original:
copy1.append(4)
print(original) # [1, 2, 3]
# Deep copy for nested lists:
import copy
nested = [[1, 2], [3, 4]]
deep = copy.deepcopy(nested)
List Comprehensions
# [expression for item in iterable if condition]
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
pairs = [(x, y) for x in range(3) for y in range(3) if x != y]
# Nested comprehension (flatten a matrix)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
Tuples
Tuples are immutable ordered sequences.
# Creating tuples
empty = ()
single = (42,) # IMPORTANT: trailing comma for single-element
coords = (3, 4)
rgb = (255, 128, 0)
nested = (1, (2, 3), 4)
# Tuple packing/unpacking
point = 3, 4 # packing
x, y = point # unpacking
a, *rest, z = (1, 2, 3, 4, 5) # a=1, rest=[2,3,4], z=5
Why Use Tuples?
# 1. Immutable โ can't accidentally change
COLORS = ("red", "green", "blue")
# 2. Can be dict keys (lists can't!)
grid = {(0, 0): "A", (1, 2): "B"}
# 3. Named tuples for clarity:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y) # 3 4
print(p[0], p[1]) # 3 4 (still indexable)
distance = (p.x**2 + p.y**2)**0.5
Exercises
Exercise 1: List Manipulation
Starting with [5, 3, 8, 1, 9, 2, 7, 4, 6]:
- Sort it
- Remove the largest value
- Insert 10 at the beginning
- Print the result
Solution:
lst = [5, 3, 8, 1, 9, 2, 7, 4, 6]
lst.sort()
lst.pop() # removes 9 (largest after sort)
lst.insert(0, 10)
print(lst) # [10, 1, 2, 3, 4, 5, 6, 7, 8]
Exercise 2: Matrix Operations
Given a 3ร3 matrix, compute the sum of the diagonal elements.
Solution:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
diagonal_sum = sum(matrix[i][i] for i in range(len(matrix)))
print(diagonal_sum) # 15 (1+5+9)
Exercise 3: Rotate List
Rotate a list k positions to the right: [1,2,3,4,5] with k=2 โ [4,5,1,2,3].
Solution:
def rotate_right(lst, k):
n = len(lst)
k = k % n
return lst[-k:] + lst[:-k]
print(rotate_right([1, 2, 3, 4, 5], 2)) # [4, 5, 1, 2, 3]