How do you iterate over elements of a tuple in Python?
Here are five examples demonstrating different methods to iterate over elements of a tuple in Python:
- Using a for loop:
my_tuple = (1, 2, 3, 4, 5)
for element in my_tuple:
print(element)
- Using tuple unpacking in a for loop:
my_tuple = (1, 2, 3, 4, 5)
for x in my_tuple:
print(x)
- Using the range function and indexing:
my_tuple = (1, 2, 3, 4, 5)
for i in range(len(my_tuple)):
print(my_tuple[i])
- Using enumerate():
my_tuple = (1, 2, 3, 4, 5)
for index, value in enumerate(my_tuple):
print(f"Index: {index}, Value: {value}")
- Using a while loop with indexing:
my_tuple = (1, 2, 3, 4, 5)
index = 0
while index < len(my_tuple):
print(my_tuple[index])
index += 1
These examples demonstrate different approaches to iterate over elements of a tuple in Python, including for loops, tuple unpacking, range function, enumerate, and while loop. Each method achieves the same result but may vary in terms of readability and efficiency depending on the specific use case.