9 of 20 topics completed
Lists and Tuples in Python
Lists and tuples are like containers that hold multiple items in a single variable. They're some of the most useful and common data structures you'll use in Python.
Real-World Examples
Think of lists and tuples like this:
- Shopping list - A list of items that can change as you add or remove things
- Student grades - A collection of scores for different assignments
- Coordinates on a map - Fixed points that don't change (x, y)
- RGB color values - Fixed triplets like (255, 0, 0) for red
Quick Overview
Lists
- • Mutable - Can be changed after creation
- • Created with square brackets:
["apple", "banana"]
- • Like a shopping list you can add to or cross off
- • Items are ordered and can be accessed by position
Tuples
- • Immutable - Cannot be changed after creation
- • Created with parentheses:
(1, 2, 3)
- • Like a date (month, day, year) that shouldn't change
- • Faster and safer than lists for fixed data
Creating Your First List
A list is simply a collection of items in square brackets, separated by commas. Lists can contain any type of data - numbers, strings, booleans, or even other lists!
1# Creating your first list2fruits = ["apple", "banana", "orange"]3print(fruits) # Output: ['apple', 'banana', 'orange']45# Lists can contain different types of data6mixed_list = [1, "hello", 3.14, True]7print(mixed_list) # Output: [1, 'hello', 3.14, True]89# Empty list10empty_list = []11print(empty_list) # Output: []1213# List of numbers14numbers = [1, 2, 3, 4, 5]15print(numbers) # Output: [1, 2, 3, 4, 5]
Accessing List Items
You can access individual items in a list using their index (position). Remember that Python uses zero-based indexing, which means the first item is at position 0, not 1.
Item | "apple" | "banana" | "orange" |
---|---|---|---|
Index (Forward) | 0 | 1 | 2 |
Index (Backward) | -3 | -2 | -1 |
1fruits = ["apple", "banana", "orange"]23# Accessing by index (position)4first_fruit = fruits[0] # "apple" (first item)5second_fruit = fruits[1] # "banana" (second item)6last_fruit = fruits[2] # "orange" (third item)78# Negative indexing (counting from the end)9last_fruit = fruits[-1] # "orange" (last item)10middle_fruit = fruits[-2] # "banana" (second-to-last item)1112# Trying to access an index that doesn't exist13# print(fruits[3]) # This would cause an IndexError1415# Checking if an item is in the list16if "banana" in fruits:17 print("Yes, banana is in the fruits list!")1819# Getting the length of a list20num_fruits = len(fruits) # 3
Slicing Lists
Slicing lets you extract a portion of a list. The syntax is list[start:end]
, where start
is included but end
is not.
1fruits = ["apple", "banana", "orange", "grape", "mango"]23# Slicing [start:end] - end index is NOT included4first_two = fruits[0:2] # ["apple", "banana"]5# Shorthand for starting at 06first_two = fruits[:2] # ["apple", "banana"]78# Get the last 2 items9last_two = fruits[-2:] # ["grape", "mango"]1011# Get a middle section12middle = fruits[1:4] # ["banana", "orange", "grape"]1314# Slicing with step [start:end:step]15every_other = fruits[::2] # ["apple", "orange", "mango"]1617# Reverse a list18reversed_fruits = fruits[::-1] # ["mango", "grape", "orange", "banana", "apple"]
Modifying Lists
One of the most powerful features of lists is that they're mutable - meaning you can change them after creating them. You can add, remove, or change items in a list.
1fruits = ["apple", "banana", "orange"]23# Adding items4fruits.append("grape") # Add to the end: ["apple", "banana", "orange", "grape"]5fruits.insert(1, "mango") # Insert at position 1: ["apple", "mango", "banana", "orange", "grape"]6fruits.extend(["kiwi", "melon"]) # Add multiple items: ["apple", "mango", "banana", "orange", "grape", "kiwi", "melon"]78# Removing items9fruits.remove("banana") # Remove by value: ["apple", "mango", "orange", "grape", "kiwi", "melon"]10popped = fruits.pop() # Remove and return last item: "melon"11popped_index = fruits.pop(1) # Remove and return item at index 1: "mango"12del fruits[0] # Delete by index: ["orange", "grape", "kiwi"]1314# Changing items15fruits[0] = "pineapple" # Replace first item: ["pineapple", "grape", "kiwi"]1617# Other useful methods18fruits.clear() # Remove all items: []19fruits = ["apple", "banana", "orange", "banana"]20count = fruits.count("banana") # Count occurrences of "banana": 221index = fruits.index("orange") # Find position of "orange": 2
Sorting and Reversing Lists
Python makes it easy to sort and rearrange your lists.
1# Sorting lists2numbers = [3, 1, 4, 1, 5, 9]3numbers.sort() # Sort in place: [1, 1, 3, 4, 5, 9]4numbers.sort(reverse=True) # Sort in descending order: [9, 5, 4, 3, 1, 1]56# If you don't want to modify the original list7original = [3, 1, 4, 1, 5, 9]8sorted_numbers = sorted(original) # Returns a new sorted list9print(original) # Original is unchanged: [3, 1, 4, 1, 5, 9]10print(sorted_numbers) # New sorted list: [1, 1, 3, 4, 5, 9]1112# Reversing lists13fruits = ["apple", "banana", "orange"]14fruits.reverse() # Reverse in place: ["orange", "banana", "apple"]1516# Alternative way to reverse without modifying original17original = ["apple", "banana", "orange"]18reversed_fruits = list(reversed(original)) # ["orange", "banana", "apple"]
⚠️ Beginner Tips
- •
list.sort()
changes the original list, whilesorted(list)
returns a new list - • Always check if your list has the expected items using
print()
when you're learning - • Be careful with indices - trying to access an index that doesn't exist will cause an error
- • Remember that lists are 0-indexed, so the first item is at position 0
Working with Tuples
Tuples are similar to lists but with one big difference: they can't be changed after creation (they're immutable). This makes them perfect for data that shouldn't change, like the days of the week or coordinates.
1# Creating tuples2coordinates = (10, 20) # A simple tuple3rgb_color = (255, 0, 0) # RGB for red4days = ("Monday", "Tuesday", "Wednesday")56# Creating a tuple with one item (notice the comma)7single_item = (42,) # The comma is necessary!8not_a_tuple = (42) # This is just a number in parentheses910# Converting other data types to tuples11tuple_from_list = tuple(["apple", "banana"]) # ("apple", "banana")12tuple_from_string = tuple("hello") # ('h', 'e', 'l', 'l', 'o')1314# Accessing tuple elements (just like lists)15first_day = days[0] # "Monday"16last_coord = coordinates[-1] # 20
Why Use Tuples?
You might wonder why we need tuples if lists seem more flexible. Here are some reasons:
- Safety - Tuples prevent accidental modification of data that shouldn't change
- Performance - Tuples are slightly faster than lists
- Dictionary keys - Tuples can be used as dictionary keys, while lists cannot
- Multiple return values - Functions often return tuples to provide multiple values
Tuple Unpacking
One of the most useful features of tuples is unpacking, which lets you assign multiple variables at once.
1# Tuple unpacking2coordinates = (10, 20)3x, y = coordinates # x = 10, y = 2045# Swap variables easily6a, b = 1, 27a, b = b, a # Now a = 2, b = 189# Returning multiple values from a function10def get_user():11 return ("Alice", 25, "alice@example.com")1213name, age, email = get_user()14print(f"{name} is {age} years old") # "Alice is 25 years old"1516# Extended unpacking (Python 3+)17first, *middle, last = (1, 2, 3, 4, 5)18# first = 1, middle = [2, 3, 4], last = 5
Lists vs. Tuples: When to Use Each
Use Lists When:
- You need to add/remove items
- The collection will change over time
- You need sorting or other list methods
- Example: A shopping list, task list
Use Tuples When:
- Data should not change
- You need a slight performance boost
- You want to use it as a dictionary key
- Example: Coordinates, RGB color values
Common Operations on Lists and Tuples
Many operations work the same way on both lists and tuples. Here are some common techniques for working with both types of sequences.
1# Checking membership2fruits = ["apple", "banana", "orange"]3coords = (10, 20, 30)45"apple" in fruits # True640 in coords # False78# Finding length9len(fruits) # 310len(coords) # 31112# Concatenation13more_fruits = fruits + ["grape"] # Combine lists14more_coords = coords + (40, 50) # Combine tuples1516# Repetition17zeros = [0] * 3 # [0, 0, 0]18pattern = (1, 2) * 2 # (1, 2, 1, 2)1920# Min and Max21min(coords) # 1022max(coords) # 302324# Sum25sum(coords) # 602627# Iterating through items28for fruit in fruits:29 print(fruit)3031# Getting index and value with enumerate32for i, fruit in enumerate(fruits):33 print(f"{i}: {fruit}") # "0: apple", "1: banana", etc.3435# Combining multiple sequences with zip36names = ["Alice", "Bob"]37scores = (95, 87)38for name, score in zip(names, scores):39 print(f"{name}: {score}") # "Alice: 95", "Bob: 87"
List Comprehensions (Bonus)
List comprehensions are a powerful and concise way to create lists. They can replace multiple lines of code with a single line.
1# Instead of:2squares = []3for i in range(1, 6):4 squares.append(i * i)5print(squares) # [1, 4, 9, 16, 25]67# You can do:8squares = [i * i for i in range(1, 6)]9print(squares) # [1, 4, 9, 16, 25]1011# With conditions12even_squares = [i * i for i in range(1, 11) if i % 2 == 0]13print(even_squares) # [4, 16, 36, 64, 100]1415# You can also convert to a tuple if needed16even_squares_tuple = tuple(i * i for i in range(1, 11) if i % 2 == 0)
🎯 Practice Exercise
Try these exercises to practice working with lists and tuples:
1# 1. Shopping List2# Create a shopping list and perform these operations:3# - Add "milk", "bread", and "eggs" to the list4# - Check if "bread" is in the list5# - Add "cheese" and "apples"6# - Remove "eggs" from the list7# - Sort the list alphabetically8# - Print the final list910# 2. Student Grades11# Create a list of tuples where each tuple contains (student_name, grade)12# For example: [("Alice", 92), ("Bob", 85), ("Charlie", 90)]13# Write code to:14# - Print the name of the student with the highest grade15# - Calculate the average grade16# - Add a new student with their grade17# - Print all students with grades above 901819# 3. To-Do List Manager20# Create a simple to-do list program that allows the user to:21# - Add tasks22# - Mark tasks as completed23# - Remove tasks24# - View all tasks25# - View only incomplete tasks
Related Tutorials
Learn about Python dictionaries and how to work with key-value pairs.
Learn moreUnderstand how to work with unique collections in Python.
Learn moreMaster loops and conditional statements.
Learn more