Tuples
๐จ๐ Technique Card: Python Tuples
๐ง What This Teaches
How to create and use tuples in Python, how they're different from lists, and when you might want to use them.
๐งฐ You Will Use
()
round brackets- Index numbers starting from 0
- Tuple unpacking
.count()
and.index()
methods
๐งฑ What is a Tuple?
A tuple is like a list โ it holds a group of items.
But unlike a list, a tuple cannot be changed (we say it's immutable).
fruit_tuple = ("apple", "banana", "cherry")
- Items in a tuple are ordered
- You can access them just like a list:
print(fruit_tuple[1]) # banana
๐ Why Use a Tuple Instead of a List?
Think of a tuple like a sealed box. Once you put things in, no one can change whatโs inside. This is helpful when:
- โ You want to protect your data so no one (even you!) changes it by accident.
- โ Youโre sending or using fixed info, like coordinates, colours, settings, or labels.
- โ You want your code to run a little faster โ Python can deal with tuples more quickly than lists.
- โ Youโre using dictionary keys โ only unchangeable things like strings and tuples can be used as keys.
๐ง Imagine:
Youโre storing a list of favourite numbers. But if that list should never change once chosen, using a tuple makes sure it stays safe and locked.
favourites = (3, 7, 42)
๐ง Common Use Cases
โ Grouping coordinates:
position = (10, 20)
โ Returning multiple values from a function:
def get_info():
return ("Alice", 10)
name, age = get_info()
โ Pairing data in a fixed structure:
pair = ("dog", "bark")
๐ซ Tuples Can't Be Changed
my_tuple = (1, 2, 3)
my_tuple[0] = 99 # โ This will give an error!
๐ก Tuple Tricks
Tuple with one item:
lonely = ("single",) # Don't forget the comma!
Use tuple()
to convert a list:
nums = [1, 2, 3]
nums_tuple = tuple(nums)
๐งฎ Methods You Can Use
example = ("apple", "banana", "apple")
print(example.count("apple")) # 2
print(example.index("banana")) # 1
๐ฒ Practise!
Try these:
weather_today = ("sunny", 20)
print("Today it is", weather_today[0], "and", weather_today[1], "degrees.")
Or create a list of city-weather tuples!
cities = [("London", 15), ("Paris", 18), ("Oslo", 10)]
๐ Linked Cards
- ๐ Technique Card: Lists in Python (practical)
- ๐ Technique Card: Python Indexing (practical)
- ๐ Technique Card: Dictionaries in Python (practical)