How we can iterate through list of tuples in Python

How we can iterate through list of tuples in Python

Iterating through a list of tuples in Python is straightforward and can be accomplished using a standard for-loop. You can either unpack the tuple values directly in the loop definition or access them using indices.

Here are some examples to illustrate different ways to iterate through a list of tuples:

1. Basic Iteration:

Iterate through the list without unpacking tuple values.

list_of_tuples = [(1, 'a'), (2, 'b'), (3, 'c')] for tup in list_of_tuples: print(tup) 

Output:

(1, 'a') (2, 'b') (3, 'c') 

2. Unpacking in the Loop:

Unpack tuple values directly in the loop.

for num, char in list_of_tuples: print(num, char) 

Output:

1 a 2 b 3 c 

3. Accessing using Indices:

Access tuple values using indices.

for tup in list_of_tuples: print(tup[0], tup[1]) 

Output:

1 a 2 b 3 c 

4. Using enumerate():

If you also want the index of the tuple in the list, you can use enumerate().

for idx, (num, char) in enumerate(list_of_tuples): print(f"Index: {idx}, Number: {num}, Char: {char}") 

Output:

Index: 0, Number: 1, Char: a Index: 1, Number: 2, Char: b Index: 2, Number: 3, Char: c 

Choose the method that best fits your needs and the structure of your tuple.


More Tags

icu aggregate quicksort celery process-elevation opera ssms-2017 real-time-data capitalization spring-mongo

More Programming Guides

Other Guides

More Programming Examples