SwadhyAI Notes

All Python notes

Python Tuples 📦

What is a Tuple?

A tuple is a collection which is ordered and unchangeable (immutable). Tuples are written with round brackets.

🔒 Analogy: The Sealed Box

Think of a tuple as a sealed clear box.
You can see what's inside (read/access), and the items stay in the order you put them in.
But once you seal it, you cannot add, remove, or swap items. It's permanent.

✨ Creating Tuples

python
thistuple = ("apple", "banana", "cherry")
print(thistuple)

# Tuple with one item (Note the comma!)
one_item = ("apple",)
not_a_tuple = ("apple") # This is a string

🔒 Why use Tuples?

Since tuples are immutable, they are faster than lists and protect data from accidental changes.

⚠️ Immutable

You cannot add, remove, or change items after the tuple is created.

python
x = ("apple", "banana", "cherry")
x[1] = "kiwi" # TypeError: 'tuple' object does not support item assignment

📦 Unpacking Tuples

When we create a tuple, we normally assign values to it. This is called "packing". But, we can also extract the values back into variables. This is called "unpacking".

python
fruits = ("apple", "banana", "cherry")

(green, yellow, red) = fruits

print(green)  # apple
print(yellow) # banana
print(red)    # cherry

✨ Pro Tip: Using Asterisk *

If the number of variables is less than the number of values, you can add an * to the variable name and the values will be assigned to the variable as a list.

python
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")

(green, yellow, *red) = fruits

print(red) # ['cherry', 'strawberry', 'raspberry']

🎯 Real-World Application: GPS Coordinates

Tuples are perfect for data that shouldn't change, like geographic coordinates.

python
# Latitude and Longitude for New York City
nyc_coords = (40.7128, -74.0060)

# You wouldn't want to accidentally change the location of a city!
# nyc_coords[0] = 100  # Error! Protected.

💡 Did You Know?

You can join two or more tuples using the + operator:

python
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2
print(tuple3)