Lists and Tuples
Python Programming
Lists and Tuples
Lists and tuples are Python's two primary ordered sequence types. A list is a mutable, ordered collection of items that can hold elements of any type. A tuple is similar but immutable — once created, its elements cannot be changed. Understanding when to use each is crucial for writing efficient and correct Python programs. Lists are the workhorse data structure you will use most often, while tuples are ideal for fixed collections of related values.
Creating and Using Lists
Lists are created using square brackets or the list() constructor. They can contain any mix of data types, including other lists (nested lists).
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True, None]
empty = []
nested = [[1, 2], [3, 4], [5, 6]]
# Accessing elements
print(fruits[0]) # "apple"
print(fruits[-1]) # "cherry"
print(nested[1][0]) # 3
# Slicing (works like strings)
print(numbers[1:4]) # [2, 3, 4]
print(numbers[::2]) # [1, 3, 5]
print(numbers[::-1]) # [5, 4, 3, 2, 1]
# Length
print(len(fruits)) # 3
Modifying Lists
Lists are mutable, meaning you can add, remove, and change elements after creation. Python provides many methods for list manipulation.
fruits = ["apple", "banana", "cherry"]
# Adding elements
fruits.append("date") # Add to end: ['apple','banana','cherry','date']
fruits.insert(1, "blueberry") # Insert at index 1
fruits.extend(["elderberry", "fig"]) # Add multiple items
# Removing elements
fruits.remove("banana") # Remove first occurrence
last = fruits.pop() # Remove and return last item
first = fruits.pop(0) # Remove and return item at index
del fruits[0] # Delete by index
# fruits.clear() # Remove all elements
# Modifying elements
numbers = [1, 2, 3, 4, 5]
numbers[0] = 10 # [10, 2, 3, 4, 5]
numbers[1:3] = [20, 30] # [10, 20, 30, 4, 5]
# Sorting
scores = [85, 92, 78, 95, 88]
scores.sort() # In-place: [78, 85, 88, 92, 95]
scores.sort(reverse=True) # Descending: [95, 92, 88, 85, 78]
sorted_scores = sorted(scores) # Returns new sorted list
# Other useful methods
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(numbers.count(1)) # 2
print(numbers.index(5)) # 4 (first occurrence)
numbers.reverse() # Reverses in place
# Copying lists (important!)
original = [1, 2, 3]
shallow = original.copy() # or original[:] or list(original)
shallow[0] = 99
print(original) # [1, 2, 3] — unchanged
Tuples
Tuples are created using parentheses or the tuple() constructor. They support indexing and slicing but not modification. Tuples are often used for function return values, dictionary keys, and any data that should not change.
# Creating tuples
point = (3, 4)
rgb = (255, 128, 0)
single = (42,) # Note the comma — without it, it's just an int
empty = ()
from_list = tuple([1, 2, 3])
# Accessing elements
print(point[0]) # 3
print(rgb[-1]) # 0
print(rgb[0:2]) # (255, 128)
# Tuples are immutable
# point[0] = 5 # TypeError!
# Tuple unpacking
x, y = point
print(f"x={x}, y={y}") # x=3, y=4
# Unpacking with * (rest operator)
first, *rest = (1, 2, 3, 4, 5)
print(first) # 1
print(rest) # [2, 3, 4, 5]
# Swapping variables (tuple packing/unpacking)
a, b = 10, 20
a, b = b, a # Now a=20, b=10
# Named tuples for readability
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y) # 3 4
List vs Tuple: When to Use Which
Use lists when you need a mutable collection that will change over time — adding items, removing items, or sorting. Use tuples when you have a fixed collection of related values that should not change, such as coordinates, RGB colors, or database records. Tuples are also slightly faster than lists and can be used as dictionary keys (lists cannot).
# Tuple as dictionary key (lists cannot be used as keys)
locations = {}
locations[(40.7128, -74.0060)] = "New York"
locations[(51.5074, -0.1278)] = "London"
# Function returning multiple values (returns a tuple)
def get_min_max(numbers):
return min(numbers), max(numbers)
lo, hi = get_min_max([3, 1, 4, 1, 5, 9])
print(f"Min: {lo}, Max: {hi}") # Min: 1, Max: 9
Pro tip: When you need a list of items that will never change, use a tuple instead. It communicates intent to other developers and provides a small performance benefit. The namedtuple from the collections module adds attribute access for even better readability.
Key Takeaways
- Lists are mutable ordered collections created with
[]; tuples are immutable ordered collections created with(). - Use
append(),insert(),extend(),remove(),pop(), andsort()to modify lists. - Tuple unpacking (
x, y = point) is a powerful Python feature for extracting values. - Use lists for collections that change; use tuples for fixed groups of related values.
- Always use
.copy()or slicing[:]to create independent copies of lists to avoid shared-reference bugs.