0

Just wondering how to iterate over a list of tuples and also iterate through the items inside the tuples at the same time.

# I am able iterate over a list of tuples like this,
fruit_list = [('banana','apple','mango'),('strawberry', 'blueberry','raspberry')]
for fruit_tup in fruit_list:
    print(fruit_tup)

#output:
#('banana', 'apple', 'mango')
#('strawberry', 'blueberry', 'raspberry')

# Iterate through the items inside the tuples as so,
for (item1,item2,item3) in fruit_list:
    print(item1,item2,item3)

#output:
#banana apple mango
#strawberry blueberry raspberry

# This is incorrect but I tried to iterate over the tuples and the items inside the tuples as so
for fruit_tup,(item1,item2,item3) in fruit_list:
    print(fruit_tup,item1,item2,item3)

#required output:
#('banana', 'apple', 'mango') banana apple mango
#('strawberry', 'blueberry', 'raspberry') strawberry blueberry raspberry

Any idea on how to do this?

Joe Ferndz
  • 8,163
  • 2
  • 11
  • 32
imantha
  • 1,990
  • 14
  • 35

3 Answers3

2

You need a nested loop:

fruit_list = [('banana','apple','mango'),('strawberry', 'blueberry','raspberry')]
for fruit_tup in fruit_list:
    for fruit in fruit_tup:
        print(fruit, end=' ') # no newline but a single space
    print() # now do a newline

Prints:

banana apple mango
strawberry blueberry raspberry
Booboo
  • 29,245
  • 3
  • 32
  • 48
0

You can do the bellow:

for lst in fruit_list:
    for fruit in lst:
        print(fruit, end=' ')
    print()
KetZoomer
  • 2,258
  • 2
  • 11
  • 33
-1

To create a list of your outputs:

lst = [('banana','apple','mango'),('strawberry', 'blueberry','raspberry')]
output = [" ".join(tupel) for tupel in lst]

If you directly want to print them:

[print(" ".join(tupel)) for tupel in lst]

If you want to loop through the tupels and the list at the same time:

output = [fruit for tupel in lst for fruit in tupel]
Andreas
  • 7,669
  • 3
  • 9
  • 30
  • printing in list comprehension is not advised. – KetZoomer Aug 02 '20 at 18:01
  • List compheresion was to made to create a list. – KetZoomer Aug 02 '20 at 18:03
  • Because it is very anti-Pythonic. See: [Is it Pythonic to use list comprehensions for just side effects? ](https://stackoverflow.com/questions/5753597/is-it-pythonic-to-use-list-comprehensions-for-just-side-effects) – Booboo Aug 02 '20 at 18:06