Python tuples are iterable collections of items. They are immutable, ordered, and indexed array-like objects that permit duplicates.
This post is all about how to iterate through tuples. This post covers,
- how to loop through elements of a tuple;
- how to iterate using indexes in tuples;
- how to loop using enumerators in a tuple;
- how to loop through tuple elements in a range;
- skipping items when looping;
- how to perform nested iterations in a tuple, and;
- how to iterate and unpack nested tuples at the same time.
Related: How to Speed up Python Data Pipelines up to 91X?
How to loop through the elements of a tuple?
Tuples are like any other iterable in Python. You can directly loop through their elements in a for-loop.
harry_potter_charectors = (
"Harry Potter",
"Hermione Granger",
"Ron Weasley",
"Severus Snape",
"Albus Dumbledore",
)
for role in harry_potter_charectors:
print(role)
You can also loop through tuple elements inside a list comprehension. It's often the most concise and convenient way to iterate in Python.
harry_potter_charectors = (
"Harry Potter",
"Hermione Granger",
"Ron Weasley",
"Severus Snape",
"Albus Dumbledore",
)
[print(role) for role in harry_potter_charectors]
How to iterate using indexes in tuples?
Since tuples are ordered and indexed, we can access tuple elements by their indexes. If we could generate a set of indexes, we can use them to iterate over tuple elements.
For instance, we can use the range function to generate a set of numbers and iterate over them. We can then use the index to access the specific element of the tuple.
Another handy tip here is to use the length of the tuple as the upper bounding limit of our range function. This way, we could loop through all the elements in a tuple.
# Loop through an index range. We set the upper limit to the length of the tuple.
for i in range(0, len(harry_potter_charectors)):
# Get the tuple element by index
role = harry_potter_charectors[i]
print(role)
How to loop using enumerators in a tuple?
Another useful technique in Python is to use enumerators when looping through a tuple. Enumerators allow us to access both the element and it's index at the same time inside a loop.
for ix, item in enumerate(harry_potter_charectors):
print(f"{item} is the charector # {ix+1} in Harry Potter")
>>> Harry Potter is the charector # 1 in Harry Potter
>>> Hermione Granger is the charector # 2 in Harry Potter
>>> Ron Weasley is the charector # 3 in Harry Potter
>>> Severus Snape is the charector # 4 in Harry Potter
>>> Albus Dumbledore is the charector # 5 in Harry Potter
How to Skip items when looping over a tuple?
Sometimes, we might need to loop through only every other element of a tuple. If not elements with a fixed gap. If so, we can slice the tuple before looping over them.
Here's an example.
harry_potter_charectors = (
"Harry Potter",
"Hermione Granger",
"Ron Weasley",
"Severus Snape",
"Albus Dumbledore",
)
for role in harry_potter_charectors[::2]:
print(role)
>>> Harry Potter
>>> Ron Weasley
>>> Albus Dumbledore
How to loop through tuple elements in a range?
If you don't want to loop through all the elements but want a start and end between which to iterate, you can use a range. Essentially we're looping through a slice of our tuple.
for role in harry_potter_charectors[0:3]:
print(role)
>>> Harry Potter
>>> Hermione Granger
>>> Ron Weasley
Iterate over nested tuples.
Tuples can hold any data in them. Which means it can have other tuples inside a tuple. We call them nested tuples.
Nested tuples are very common in Python. We could also perform a nested iteration on them.
harry_potter_hose_charactors = (
("Harry Potter", "Hermione Granger", "Ron Weasley"),
("Severus Snape", "Draco Malfoy", "Lord Voldemort"),
("Luna Lovegood", "Quirinus Quirrell", "Cho Chang"),
("Hannah Abbott", "Fat Friar Ghost", "Teddy Lupin"),
)
for house in harry_potter_hose_charactors[0:3]:
for charactor in house:
print(charactor)
>>> Harry Potter
>>> Hermione Granger
>>> Ron Weasley
>>> Severus Snape
>>> Draco Malfoy
>>> Lord Voldemort
>>> Luna Lovegood
>>> Quirinus Quirrell
>>> Cho Chang
Iterate and unpack nested tuples at the same time
We can combine tuple deconstructors on nested tuples.
Related: What Are Tuples in Python? And Everything You Should Know About Them.
The outermost loop is a regular for-loop. Inside them, we use tuple unpacking instead of looping through elements again. We can assign them to variables and access them within the code.
If any of the unpacked tuple elements is another tuple (deeply nested tuples,) and we want to iterate over its element, too, we can do it.
harry_potter_house_charactors = (
(
"Griffindor",
("Harry Potter", "Hermione Granger", "Ron Weasley"),
"Minerva McGonagall",
"Nearly Headless Nick",
),
(
"Slytherin",
("Severus Snape", "Draco Malfoy", "Lord Voldemort"),
"Horace Slughorn",
"Bloody Baron",
),
(
"Ravenclaw",
("Luna Lovegood", "Quirinus Quirrell", "Cho Chang"),
"Filius Flitwick",
"Grey Lady",
),
(
"Hufflepuff",
("Hannah Abbott", "Fat Friar Ghost", "Teddy Lupin"),
"Hufflepuff",
"Fat Friar",
),
)
for house_name, *members, head, goast in harry_potter_house_charactors:
print(f"{house_name} is a house in Harry Potter")
print(f"{head} is the head of the house")
print(f"{goast} is the goast of the house")
for member in members:
print(f"{member} is a member of the house")
print("\n")
>>> Griffindor is a house in Harry Potter
>>> Minerva McGonagall is the head of the house
>>> Nearly Headless Nick is the goast of the house
>>> ('Harry Potter', 'Hermione Granger', 'Ron Weasley') is a member of the house
>>> Slytherin is a house in Harry Potter
>>> Horace Slughorn is the head of the house
>>> Bloody Baron is the goast of the house
>>> ('Severus Snape', 'Draco Malfoy', 'Lord Voldemort') is a member of the house
>>> Ravenclaw is a house in Harry Potter
>>> Filius Flitwick is the head of the house
>>> Grey Lady is the goast of the house
>>> ('Luna Lovegood', 'Quirinus Quirrell', 'Cho Chang') is a member of the house
>>> Hufflepuff is a house in Harry Potter
>>> Hufflepuff is the head of the house
>>> Fat Friar is the goast of the house
>>> ('Hannah Abbott', 'Fat Friar Ghost', 'Teddy Lupin') is a member of the house
Related posts: