Lists
Create, access, modify, sort, and comprehend
Skills taught: python.list, python.indexing, python.slicing, python.list-methods, python.list-comprehension
Creating and accessing lists
# Create a list
fruits = ['apple', 'banana', 'cherry']
numbers = [1, 2, 3, 4, 5]
mixed = [42, 'hello', True, None] # can mix types
empty = []
# Access by index (starts at 0)
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[-1]) # cherry (last item)
print(fruits[-2]) # banana (second to last)
# Slicing [start:stop:step]
print(numbers[1:4]) # [2, 3, 4]
print(numbers[:3]) # [1, 2, 3] (first 3)
print(numbers[2:]) # [3, 4, 5] (from index 2)
print(numbers[::2]) # [1, 3, 5] (every other)
print(numbers[::-1]) # [5, 4, 3, 2, 1] (reversed)
Modifying lists
fruits = ['apple', 'banana', 'cherry']
# Add items
fruits.append('date') # add to end
fruits.insert(1, 'apricot') # insert at index 1
fruits.extend(['elderberry', 'fig']) # add multiple
# Remove items
fruits.remove('banana') # remove by value
pop_item = fruits.pop() # remove and return last
pop_item2 = fruits.pop(0) # remove and return at index
del fruits[0] # delete at index
# Useful methods
fruits.sort() # sort in place (A-Z)
fruits.sort(reverse=True) # sort Z-A
new_list = sorted(fruits) # returns new sorted list
fruits.reverse() # reverse in place
print(len(fruits)) # number of items
print('apple' in fruits) # True/False membership
print(fruits.count('apple')) # how many times 'apple' appears
print(fruits.index('cherry')) # index of first 'cherry'
List comprehensions
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# [expression for item in iterable]
squares = [n ** 2 for n in numbers]
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# [expression for item in iterable if condition]
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# Transform strings
words = [' hello ', 'WORLD', 'python']
clean = [w.strip().lower() for w in words]
print(clean) # ['hello', 'world', 'python']
# Nested — flatten a 2D list
matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [n for row in matrix for n in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
Frequently Asked Questions
What is the difference between sort() and sorted()?
list.sort() sorts the list in place and returns None — it modifies the original. sorted(list) returns a NEW sorted list without modifying the original. Use sorted() when you need to keep the original, sort() when you don't.
How do I copy a list?
new = old.copy() or new = old[:] or new = list(old) — all create a shallow copy. For nested lists, use import copy; new = copy.deepcopy(old).