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]
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With