You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Lists and tuples are Python's most fundamental sequence data structures. Both store ordered collections of items, but they differ in mutability: lists can be changed after creation, tuples cannot.
A list is an ordered, mutable collection defined with square brackets:
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
empty = []
Items are accessed by zero-based index:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry (negative index from end)
print(fruits[1:3]) # ['banana', 'cherry'] (slicing)
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry" # replace item
fruits.append("mango") # add to end
fruits.insert(1, "avocado") # insert at index
fruits.remove("apple") # remove by value
popped = fruits.pop() # remove and return last item
popped_at = fruits.pop(0) # remove and return at index
nums = [3, 1, 4, 1, 5, 9]
nums.sort() # sorts in place
nums.reverse() # reverses in place
print(len(nums)) # 6 — number of items
print(nums.count(1)) # 2 — count occurrences
print(nums.index(4)) # index of first occurrence
A concise way to build lists:
squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
A tuple is an ordered, immutable collection defined with parentheses:
point = (3, 7)
rgb = (255, 128, 0)
single = (42,) # trailing comma required for single-element tuple
You access tuple items the same way as lists, but you cannot modify them:
point = (3, 7)
print(point[0]) # 3
# point[0] = 10 # TypeError: tuple is immutable
Use tuples for data that should not change — coordinates, RGB colors, database records returned from a query. Use lists when you need to add, remove, or reorder items.
coordinates = (10, 20, 30)
x, y, z = coordinates
print(x, y, z) # 10 20 30
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # True
print("grape" not in fruits) # True
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.