Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Iterate through list of list to make a new list in index sequence

Tags:

python

How would you iterate through a list of lists, such as:

[[1,2,3,4], [5,6], [7,8,9]]

and construct a new list by grabbing the first item of each list, then the second, etc. So the above becomes this:

[1, 5, 7, 2, 6, 8, 3, 9, 4]
like image 930
patrickb Avatar asked Mar 10 '16 22:03

patrickb


People also ask

Does Python iterate through lists in order?

When you iterate over a sequence (list, tuple, etc.), the order is guaranteed. Hashed structures (dict, set, etc.) have their own order -- but for a given structure, the order will be the same each time.

How do you start a for loop at a different index in Python?

If you want to iterate through a list from a second item, just use range(1, nI) (if nI is the length of the list or so). i. e. Please, remember: python uses zero indexing, i.e. first element has an index 0, the second - 1 etc. By default, range starts from 0 and stops at the value of the passed parameter minus one.

How do you modify a list while iterating?

To avoid this problem, a simple solution is to iterate over a copy of the list. For example, you'll obtain a copy of list_1 by using the slice notation with default values list_1[:] . Because you iterate over a copy of the list, you can modify the original list without damaging the iterator.


1 Answers

You can use a list comprehension along with itertools.izip_longest (or zip_longest in Python 3)

from itertools import izip_longest
a = [[1,2,3,4], [5,6], [7,8,9]]
[i for sublist in izip_longest(*a) for i in sublist if i is not None]
# [1, 5, 7, 2, 6, 8, 3, 9, 4]
like image 86
Julien Spronck Avatar answered Oct 14 '22 17:10

Julien Spronck