Progress0%

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!

Python
1# Creating your first list
2fruits = ["apple", "banana", "orange"]
3print(fruits) # Output: ['apple', 'banana', 'orange']
4
5# Lists can contain different types of data
6mixed_list = [1, "hello", 3.14, True]
7print(mixed_list) # Output: [1, 'hello', 3.14, True]
8
9# Empty list
10empty_list = []
11print(empty_list) # Output: []
12
13# List of numbers
14numbers = [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)012
Index (Backward)-3-2-1
Python
1fruits = ["apple", "banana", "orange"]
2
3# 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)
7
8# Negative indexing (counting from the end)
9last_fruit = fruits[-1] # "orange" (last item)
10middle_fruit = fruits[-2] # "banana" (second-to-last item)
11
12# Trying to access an index that doesn't exist
13# print(fruits[3]) # This would cause an IndexError
14
15# Checking if an item is in the list
16if "banana" in fruits:
17 print("Yes, banana is in the fruits list!")
18
19# Getting the length of a list
20num_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.

Python
1fruits = ["apple", "banana", "orange", "grape", "mango"]
2
3# Slicing [start:end] - end index is NOT included
4first_two = fruits[0:2] # ["apple", "banana"]
5# Shorthand for starting at 0
6first_two = fruits[:2] # ["apple", "banana"]
7
8# Get the last 2 items
9last_two = fruits[-2:] # ["grape", "mango"]
10
11# Get a middle section
12middle = fruits[1:4] # ["banana", "orange", "grape"]
13
14# Slicing with step [start:end:step]
15every_other = fruits[::2] # ["apple", "orange", "mango"]
16
17# Reverse a list
18reversed_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.

Python
1fruits = ["apple", "banana", "orange"]
2
3# Adding items
4fruits.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"]
7
8# Removing items
9fruits.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"]
13
14# Changing items
15fruits[0] = "pineapple" # Replace first item: ["pineapple", "grape", "kiwi"]
16
17# Other useful methods
18fruits.clear() # Remove all items: []
19fruits = ["apple", "banana", "orange", "banana"]
20count = fruits.count("banana") # Count occurrences of "banana": 2
21index = fruits.index("orange") # Find position of "orange": 2

Sorting and Reversing Lists

Python makes it easy to sort and rearrange your lists.

Python
1# Sorting lists
2numbers = [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]
5
6# If you don't want to modify the original list
7original = [3, 1, 4, 1, 5, 9]
8sorted_numbers = sorted(original) # Returns a new sorted list
9print(original) # Original is unchanged: [3, 1, 4, 1, 5, 9]
10print(sorted_numbers) # New sorted list: [1, 1, 3, 4, 5, 9]
11
12# Reversing lists
13fruits = ["apple", "banana", "orange"]
14fruits.reverse() # Reverse in place: ["orange", "banana", "apple"]
15
16# Alternative way to reverse without modifying original
17original = ["apple", "banana", "orange"]
18reversed_fruits = list(reversed(original)) # ["orange", "banana", "apple"]

⚠️ Beginner Tips

  • list.sort() changes the original list, while sorted(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.

Python
1# Creating tuples
2coordinates = (10, 20) # A simple tuple
3rgb_color = (255, 0, 0) # RGB for red
4days = ("Monday", "Tuesday", "Wednesday")
5
6# 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 parentheses
9
10# Converting other data types to tuples
11tuple_from_list = tuple(["apple", "banana"]) # ("apple", "banana")
12tuple_from_string = tuple("hello") # ('h', 'e', 'l', 'l', 'o')
13
14# 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.

Python
1# Tuple unpacking
2coordinates = (10, 20)
3x, y = coordinates # x = 10, y = 20
4
5# Swap variables easily
6a, b = 1, 2
7a, b = b, a # Now a = 2, b = 1
8
9# Returning multiple values from a function
10def get_user():
11 return ("Alice", 25, "alice@example.com")
12
13name, age, email = get_user()
14print(f"{name} is {age} years old") # "Alice is 25 years old"
15
16# 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.

Python
1# Checking membership
2fruits = ["apple", "banana", "orange"]
3coords = (10, 20, 30)
4
5"apple" in fruits # True
640 in coords # False
7
8# Finding length
9len(fruits) # 3
10len(coords) # 3
11
12# Concatenation
13more_fruits = fruits + ["grape"] # Combine lists
14more_coords = coords + (40, 50) # Combine tuples
15
16# Repetition
17zeros = [0] * 3 # [0, 0, 0]
18pattern = (1, 2) * 2 # (1, 2, 1, 2)
19
20# Min and Max
21min(coords) # 10
22max(coords) # 30
23
24# Sum
25sum(coords) # 60
26
27# Iterating through items
28for fruit in fruits:
29 print(fruit)
30
31# Getting index and value with enumerate
32for i, fruit in enumerate(fruits):
33 print(f"{i}: {fruit}") # "0: apple", "1: banana", etc.
34
35# Combining multiple sequences with zip
36names = ["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.

Python
1# Instead of:
2squares = []
3for i in range(1, 6):
4 squares.append(i * i)
5print(squares) # [1, 4, 9, 16, 25]
6
7# You can do:
8squares = [i * i for i in range(1, 6)]
9print(squares) # [1, 4, 9, 16, 25]
10
11# With conditions
12even_squares = [i * i for i in range(1, 11) if i % 2 == 0]
13print(even_squares) # [4, 16, 36, 64, 100]
14
15# You can also convert to a tuple if needed
16even_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:

Python
1# 1. Shopping List
2# Create a shopping list and perform these operations:
3# - Add "milk", "bread", and "eggs" to the list
4# - Check if "bread" is in the list
5# - Add "cheese" and "apples"
6# - Remove "eggs" from the list
7# - Sort the list alphabetically
8# - Print the final list
9
10# 2. Student Grades
11# 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 grade
15# - Calculate the average grade
16# - Add a new student with their grade
17# - Print all students with grades above 90
18
19# 3. To-Do List Manager
20# Create a simple to-do list program that allows the user to:
21# - Add tasks
22# - Mark tasks as completed
23# - Remove tasks
24# - View all tasks
25# - View only incomplete tasks

Related Tutorials

Learn about Python dictionaries and how to work with key-value pairs.

Learn more

Understand how to work with unique collections in Python.

Learn more

Master loops and conditional statements.

Learn more