Yuri
Yuri

Reputation: 27

Python List iteration list of list

I want to iterate through a list of lists but not in the typical way such that I go through each element in the list of lists then move to the next list.

How does the logic work if I wanted to print the elements in the order 1, 4, 2, 5, 3, 6, which is the list of lists element then the lists and repeat, instead of 1, 2, 3, 4, 5, 6?

ls = [[1, 2, 3], [4, 5, 6]]

Upvotes: 1

Views: 71

Answers (5)

Aaj Kaal
Aaj Kaal

Reputation: 1284

import numpy as np

ls = [[1, 2, 3], [4, 5, 6], [7,8,9], [10,11,12]]
print(ls)
res1 = [ls[r][c] for c in range(len(ls[0])) for r in range(len(ls)) ]
print(res1)

print('-' * 30)
# Now using numpy which is generally faster
np_ls = np.array(ls)
print(np_ls)
res = [j  for i in range(len(np_ls[0])) for j in np_ls[...,i]]
print(res)

Upvotes: 0

Serial Lazer
Serial Lazer

Reputation: 1669

There's already a library function defined for this : itertools.zip_longest():

import itertools

zipped_list = itertools.zip_longest(*ls, fillvalue='-') 

This is more generic since it will automatically create items even if you have more than 2 sublists.

On top of that, it also takes care of sublists with different lengths

Upvotes: 0

DYZ
DYZ

Reputation: 57033

Transform your list of lists into a transposed flat list (technically, a tuple, but it makes no difference). zip transposes the list, sum flattens it.

indexes = sum(zip(*ls), tuple())
# (1, 4, 2, 5, 3, 6)

If you still want a list (and perhaps you do not), call list(indexes).

Upvotes: 1

Mike67
Mike67

Reputation: 11342

If you want short code

ls = [[1, 2, 3], [4, 5, 6]]
result = [v for tt in list(zip(*tuple([tuple(x) for x in ls]))) for v in tt]
print(result)

Output

[1, 4, 2, 5, 3, 6]

As suggested by @iz_, there's a shorter way for the same output

ls = [[1, 2, 3], [4, 5, 6]]
result = [v for tt in zip(*ls) for v in tt]
print(result)

Upvotes: 1

James Tollefson
James Tollefson

Reputation: 893

Assuming all the lists are the same length:

list_length = len(ls[0])
for i in range(list_length):
    for list in ls:
        print(list[i])

Upvotes: 1

Related Questions