11. Tuples in Python

Quiz: 0/5

When working with collections of data in Python, you'll encounter tuples and lists. While they may look similar, they serve different purposes and have unique characteristics. Let’s explore tuples, compare them with lists, and understand when to use each!

What are Tuples?

A tuple is like a container that holds a group of related items in a specific order. Once created, you can't change its contents.Think of it as a "locked box" of data.

Key features of Tuples:

  • Immutable: You can’t add, remove, or modify items after creation.
  • Ordered: Items stay in the same sequence you define.
  • Lightweight: Tuples are more memory-efficient than lists.
  • Purpose: Ideal for data that should remain constant, like geographic coordinates, configuration settings, or fixed groupings.

Creating and using Tuples

Tuples are created using parentheses () with items separated by commas.

Example:

# A tuple of fruits
fruits = ("apple", "banana", "cherry")
print(fruits[0])  # Output: apple

You can access tuple items just like you would with a list, using their index.

Accessing Tuple Items:

print(fruits[1])  # Output: banana

However, trying to modify a tuple will result in an error:

fruits[0] = "pear"  # TypeError: 'tuple' object does not support item assignment

Why use Tuples?

Tuples shine when you need reliable, unchanging data:

  • Coordinates: (40.7128, 74.0060) (latitude and longitude)
  • Days of the Week: ("Monday", "Tuesday", "Wednesday", ...)
  • Configuration Settings: ("read-only", "admin")

Tuples vs. Lists: What's the difference?

Tuples and lists both store collections of data, but here’s how they differ:

Feature Tuple List
Mutability Immutable (can’t be changed) Mutable (can be modified)
Syntax Use parentheses () Use square brackets []
Purpose For fixed, unchanging data For flexible, dynamic data
Size More memory-efficient Less memory-efficient
Performance Faster (due to immutability) Slower (mutable and resizeable)
Methods Limited: count(), index() Many: append(), remove(), sort(), etc.
Use Cases Coordinates, configuration settings Shopping lists, user inputs

When to use Tuples vs. Lists

Here’s a simple decision guide:

  1. Use a Tuple if:

    • The data is fixed and won’t change.
    • Example: coordinates = (10, 20)
  2. Use a List if:

    • The data might grow, shrink, or change over time.
    • Example: shopping_list = ["milk", "eggs", "bread"]

Packing and unpacking Tuples

Tuples also allow packing and unpacking, making them useful for grouping and splitting data.

Packing:

You can group multiple values into a tuple:

coordinates = (40.7128, 74.0060)

Unpacking:

Break a tuple into individual variables:

latitude, longitude = coordinates
print(latitude)   # Output: 40.7128
print(longitude)  # Output: 74.0060

Tuple methods

While tuples are immutable, they do have a few helpful methods:

count(value): Counts how many times a value appears in the tuple.

numbers = (1, 2, 3, 2, 2)
print(numbers.count(2))  # Output: 3

index(value): Returns the index of the first occurrence of a value.

print(numbers.index(3))  # Output: 2

Code comparison: Tuple vs. List

Tuple Example:

# Tuple: Fixed data
coordinates = (10, 20)
print(coordinates[0])  # Output: 10

# Trying to modify will raise an error
# coordinates[0] = 15  # TypeError: 'tuple' object does not support item assignment

List Example:

# List: Flexible data
shopping_list = ["milk", "eggs", "bread"]
shopping_list.append("butter")  # Add an item
print(shopping_list)  # Output: ['milk', 'eggs', 'bread', 'butter']

shopping_list[0] = "almond milk"  # Modify an item
print(shopping_list)  # Output: ['almond milk', 'eggs', 'bread', 'butter']

Summary

  • Tuples: Use them for unchanging data, like settings, coordinates, or constants.
  • Lists: Use them for flexible, modifiable data, like user inputs or task lists.

Understanding the strengths of each will help you write better Python code. Why not try creating your own tuple and list today?

Hands-On Practise

Exercise: Work with Tuples and compare them to Lists

You are organizing a trip and want to keep track of some travel information. Use tuples for fixed data and lists for flexible data.

Tasks:

  1. Create a tuple called trip_details that contains the following information:

    • Destination: "Paris"
    • Number of travelers: 3
    • Travel date: "2024-12-25"
  2. Print the destination and travel date from the tuple.

  3. Create a list called packing_list with items: "passport", "clothes", "toothbrush".

    • Add "camera" to the packing_list.
    • Replace "clothes" with "winter jacket".
  4. Compare the immutability of trip_details and packing_list by trying to:

    • Change the travel date in trip_details to "2024-12-26".
    • Add an item to trip_details.
      What happens in each case?
Output:

Quizzes: 0/5

Question 1:

What is the key difference between a tuple and a list in Python?

  • Tuples are immutable, while lists are mutable.
  • Lists are immutable, while tuples are mutable.
  • Tuples and lists are both mutable.
  • Tuples and lists are both immutable.

Question 2:

Which of the following methods can be used with tuples in Python?

  • append()
  • count()
  • remove()
  • pop()

Question 3:

How do you access the first element of a tuple named my_tuple?

  • my_tuple[1]
  • my_tuple.first()
  • my_tuple[0]
  • my_tuple.get(0)

Question 4:

What happens if you try to modify an element in a tuple?

  • The element is updated successfully.
  • The tuple is converted to a list automatically.
  • A TypeError is raised.
  • The tuple is deleted.

Question 5:

Which syntax creates a tuple with a single element?

  • (42)
  • (42,)
  • [42]
  • {42}

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonPython ListNext lessonDictionaries in Python