Python – Loop Tuples
In Python, a tuple is an ordered collection of elements, enclosed in parentheses. It is similar to a list, but unlike lists, tuples are immutable, meaning their values cannot be changed once they are created.
Looping through a tuple allows you to access each element in the tuple and perform operations on them. There are different ways to loop through a tuple in Python, including using a for loop or a while loop.
Using a for loop to loop through a tuple
The most common way to loop through a tuple is by using a for loop. The for loop iterates over each element in the tuple and executes a block of code for each element.
Here’s an example:
fruits = ("apple", "banana", "cherry")
for fruit in fruits:
print(fruit)
This code will output:
apple
banana
cherry
In this example, the variable “fruit” takes on the value of each element in the “fruits” tuple, one at a time. The print statement then displays the value of “fruit” on each iteration of the loop.
Using a while loop to loop through a tuple
Another way to loop through a tuple is by using a while loop. The while loop continues to execute a block of code as long as a specified condition is true.
Here’s an example:
fruits = ("apple", "banana", "cherry")
index = 0
while index < len(fruits):
print(fruits[index])
index += 1
This code will output the same result as the previous example:
apple
banana
cherry
In this example, we use a while loop to iterate through the elements of the “fruits” tuple. The variable “index” keeps track of the current position in the tuple, and the print statement displays the value at that position. After each iteration, we increment the value of “index” by 1 to move to the next element.
Looping through a tuple of tuples
In Python, you can also have a tuple that contains other tuples. This is known as a tuple of tuples. You can loop through a tuple of tuples using nested loops.
Here’s an example:
students = (("John", 20), ("Jane", 22), ("Tom", 19))
for student in students:
for item in student:
print(item)
This code will output:
John
20
Jane
22
Tom
19
In this example, the outer loop iterates through each tuple in the “students” tuple. The inner loop then iterates through each element in the current tuple, printing each element on a new line.
Conclusion
Looping through tuples in Python allows you to access and manipulate the elements within them. Whether you use a for loop or a while loop, you can iterate through a tuple and perform operations on each element. Additionally, if you have a tuple of tuples, you can use nested loops to access the elements within the inner tuples. Tuples provide a convenient way to store and work with ordered collections of data in Python.