Alex T
Alex T

Reputation: 3754

iterating two lists alternately in python

Let's say I have a list like this:

rows=[['a1','a3','a5','a7'], ['a2','a4','a6','a8']]

And I want to create new list from this, so it would look like this: ['a','1','a','2','a','3'....] and so on until 'a8' in this order, but I don't want to sort the list in any way.

My point is I want to append the values in such a way that it appends first item from first list in rows, then it appends the first item from the second list, and then goes back to the second item from the first list, and so on.

How can I do that?

Upvotes: 0

Views: 137

Answers (2)

Moses Koledoye
Moses Koledoye

Reputation: 78556

You can use zip, and then join and unwrap the items with a nested for in a list comprehension:

>>> [x for i, j in zip(*rows) for x in i+j]
['a', '1', 'a', '2', 'a', '3', 'a', '4', 'a', '5', 'a', '6', 'a', '7', 'a', '8']

You can handle lists with varying number of sublists if you collect all the items from zip in a tuple and then use str.join:

>>> [x for i in zip(*rows) for x in ''.join(i)]
['a', '1', 'a', '2', 'a', '3', 'a', '4', 'a', '5', 'a', '6', 'a', '7', 'a', '8']

Upvotes: 3

Prune
Prune

Reputation: 77847

Use a list comprehension with a nested iteration:

merged = [rows[i][j] for j in len(rows) for i in len(rows[0]]

From there, I expect that you can re-cast your two-character list into the sequence of characters you want.

Upvotes: 1

Related Questions