Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate over the tuples of the items of two or more lists in Python? [duplicate]

Tags:

python

loops

Specifically, I have two lists of strings that I'd like to combine into a string where each line is the next two strings from the lists, separated by spaces:

a = ['foo1', 'foo2', 'foo3']
b = ['bar1', 'bar2', 'bar3']

I want a function combine_to_lines() that would return:

"""foo1 bar1
foo2 bar2
foo3 bar3"""

I admit I've already solved this problem, so I'm going to post the answer. But perhaps someone else has a better one or sees a flaw in mine.

Update: I over-simplified my example above. In my real-world problem the lines were formatted in a more complicated manner that required the tuples returned from zip() to be unpacked. But kudos to mhawke for coming up to the simplest solution to this example.

like image 399
Daryl Spitzer Avatar asked Jul 31 '09 02:07

Daryl Spitzer


People also ask

How can you iterate over a tuples items?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the tuple, then start at 0 and loop your way through the tuple items by refering to their indexes. Remember to increase the index by 1 after each iteration.

How do you iterate a tuple of tuples in Python?

Easiest way is to employ two nested for loops. Outer loop fetches each tuple and inner loop traverses each item from the tuple. Inner print() function end=' ' to print all items in a tuple in one line. Another print() introduces new line after each tuple.

Can you iterate through a list of tuples?

With Python's enumerate() method you can iterate through a list or tuple while accessing both the index and value of the iterable (list or tuple) object.

Can you iterate over a tuple in Python?

We can iterate over tuples using a simple for-loop. We can do common sequence operations on tuples like indexing, slicing, concatenation, multiplication, getting the min, max value and so on.


1 Answers

It's not necessary to unpack and repack the tuples returned by zip:

'\n'.join(' '.join(x) for x in zip(a, b))
like image 156
mhawke Avatar answered Sep 30 '22 12:09

mhawke