1

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]]
1
  • Does /questions/1663807/how-to-iterate-through-two-lists-in-parallel help? Commented Nov 7, 2020 at 1:52

5 Answers 5

1

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])
Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

Why not just [v for tt in zip(*ls) for v in tt]?
1

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).

Comments

0

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

Comments

0
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.