A list is an ordered, mutable collection of items enclosed in square brackets []:
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]
empty = []
numbers = list(range(5)) # [0, 1, 2, 3, 4]
items = ["a", "b", "c", "d", "e"]
items[0] # "a"
items[-1] # "e"
items[1:3] # ["b", "c"]
items[:3] # ["a", "b", "c"]
items[::2] # ["a", "c", "e"]
items[::-1] # ["e", "d", "c", "b", "a"]
Unlike strings, lists can be modified in place:
nums = [1, 2, 3]
nums[0] = 99
print(nums) # [99, 2, 3]
lst = [1, 2, 3]
lst.append(4) # [1, 2, 3, 4]
lst.extend([5, 6]) # [1, 2, 3, 4, 5, 6]
lst.insert(0, 0) # [0, 1, 2, 3, 4, 5, 6]
lst.remove(3) # removes first 3
popped = lst.pop() # removes and returns last item
lst.pop(0) # removes and returns index 0
lst.clear() # []
lst = [3, 1, 4, 1, 5]
lst.index(4) # 2
lst.count(1) # 2
lst.sort() # [1, 1, 3, 4, 5]
lst.sort(reverse=True) # [5, 4, 3, 1, 1]
lst.reverse() # reverse in place
copy = lst.copy() # shallow copy
A concise way to create lists:
squares = [x ** 2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
pairs = [(a, b) for a in [1,2] for b in ["x","y"]]
# [(1, 'x'), (1, 'y'), (2, 'x'), (2, 'y')]
colors = ["red", "green", "blue"]
for color in colors:
print(color)
for i, color in enumerate(colors):
print(i, color)
for a, b in zip([1,2], ["x","y"]):
print(a, b)
words = ["banana", "apple", "Cherry"]
words.sort(key=str.lower) # case-insensitive sort
students = [("Alice", 85), ("Bob", 92), ("Eve", 78)]
students.sort(key=lambda s: s[1], reverse=True)
# [("Bob", 92), ("Alice", 85), ("Eve", 78)]
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
shallow[0][0] = 99 # affects original too!
deep = copy.deepcopy(original)
deep[0][0] = 100 # original unchanged
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2]) # 6
# Flatten a nested list
flat = [item for row in matrix for item in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
map() and filter() in most cases. They are also faster than manual for loops with append.
Create a list of 10 random integers between 1 and 100. Write code that: (1) prints the list sorted, (2) prints the sum and average, (3) creates a new list containing only the even numbers using list comprehension, (4) finds the second largest number, and (5) reverses the list in place. Use at least 5 different list methods.