beginner

Python Tuples

Learn to use tuples for immutable data collections in Python.

Tuples are like lists but with one key difference: they cannot be modified after creation. This immutability makes tuples perfect for data that should not change, like coordinates, RGB colors, or database records. Understanding when to use tuples versus lists is an important skill for writing robust Python code.

📚 Concepts & Theory

Creating Tuples

Tuples use parentheses (optional but recommended):

coordinates = (10, 20)
rgb = (255, 128, 0)
single = (42,)  # Note the comma!
empty = ()

Accessing Elements

Works just like lists:

point = (3, 4, 5)
x = point[0]  # 3
z = point[-1] # 5

Tuple Unpacking

A powerful Python feature:

point = (10, 20)
x, y = point  # x=10, y=20

# Swap variables
a, b = b, a

Why Use Tuples?

  • Immutable (safe from accidental changes)
  • Faster than lists
  • Can be used as dictionary keys
  • Signal intent: this data should not change
Tuple Methods

nums = (1, 2, 2, 3)
nums.count(2)  # 2
nums.index(3)  # 3

🎯 Your Challenge

Create a tuple called `rgb_red` with the values 255, 0, 0 (representing the color red). Then use tuple unpacking to assign these values to variables `r`, `g`, and `b`.

📝 Starter Code

Python
# Create RGB tuple for red color
rgb_red = 

# Unpack into r, g, b variables
r, g, b = 
  • Tuples use parentheses ()
  • For a single-element tuple, you need a trailing comma: (42,)
  • Unpacking requires the same number of variables as tuple elements

Solution

Python
rgb_red = (255, 0, 0)

r, g, b = rgb_red

Explanation

We create a tuple with three values representing RGB components. Tuple unpacking assigns each value to a separate variable in order: r gets 255, g gets 0, and b gets 0.

⚠️ Common Mistakes to Avoid

  • Forgetting the comma in single-element tuples
  • Trying to modify tuple values after creation
  • Confusing parentheses with function calls
  • Wrong number of variables when unpacking

❓ Frequently Asked Questions

Yes! You can nest tuples in lists and vice versa. This is common for storing coordinate pairs: [(0, 0), (1, 1), (2, 2)].
Use tuples when data should not change (coordinates, settings, records). Use lists when you need to add, remove, or modify elements.

🔗 Related Concepts