Python – Loop Tuples

In Python, you can loop through tuples just like you can with lists. Since tuples are ordered, you can access each element in the tuple one by one using a for loop.

1. Looping through a Tuple

You can directly loop through the elements of a tuple using a for loop.

# Tuple
my_tuple = (10, 20, 30, 40, 50)

# Loop through the tuple
for item in my_tuple:
    print(item)

Output:

10
20
30
40
50

2. Looping with Index

If you need both the index and the element, you can use the enumerate() function to get the index along with each element.

# Tuple
my_tuple = (10, 20, 30, 40, 50)

# Loop with index
for index, value in enumerate(my_tuple):
    print(f"Index: {index}, Value: {value}")

Output:

Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30
Index: 3, Value: 40
Index: 4, Value: 50

3. Looping through Nested Tuples

If a tuple contains other tuples (nested tuples), you can loop through both the outer and inner tuples.

# Nested tuple
my_tuple = (1, (2, 3), 4, (5, 6))

# Loop through the tuple
for item in my_tuple:
    if isinstance(item, tuple):  # Check if the item is a tuple
        for sub_item in item:
            print(sub_item)
    else:
        print(item)

Output:

1
2
3
4
5
6

4. Looping Using List Comprehension

You can also loop through a tuple using list comprehension to create a new list based on the elements of the tuple.

# Tuple
my_tuple = (10, 20, 30, 40, 50)

# Create a list of squares using list comprehension
squares = [x ** 2 for x in my_tuple]

print(squares)  # Output: [100, 400, 900, 1600, 2500]

5. Using map() Function for Iteration

You can also use the map() function to apply a function to each element in a tuple.

# Tuple
my_tuple = (1, 2, 3, 4, 5)

# Use map to square each element
squares = map(lambda x: x ** 2, my_tuple)

# Convert map object to list and print
print(list(squares))  # Output: [1, 4, 9, 16, 25]

6. Looping Through a Tuple with Conditional Statements

You can apply conditional statements within a loop to filter elements based on certain conditions.

# Tuple
my_tuple = (10, 15, 20, 25, 30, 35)

# Loop with conditional check
for item in my_tuple:
    if item % 2 == 0:
        print(f"Even number: {item}")
    else:
        print(f"Odd number: {item}")

Output:

Even number: 10
Odd number: 15
Even number: 20
Odd number: 25
Even number: 30
Odd number: 35

Summary of Looping through Tuples:

  • Basic loop: Use for item in my_tuple to loop through each element.
  • Index and element: Use enumerate() to get both index and element during iteration.
  • Nested tuples: Use nested loops to iterate over inner tuples.
  • List comprehension: Create new lists based on tuple elements.
  • map() function: Apply a function to each element of the tuple.
  • Conditional statements: Use if conditions to filter or modify elements during iteration.
Leave a Reply 0

Your email address will not be published. Required fields are marked *