6

I want to return a list with the interleaved elements of two lists directly from the list comprehension - without use a next step to flaten the result. Is it possible?

alist1_temp=[1, 4,2]
alist2_temp=[3, 7,4]
t=[[x,y] for x,y in zip(alist1_temp, alist2_temp)]

Return [[1, 3], [4, 7],[2, 4]]

But how can I get directly from the list-comprehension [1, 3, 4, 7, 2, 4]?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Pedro Pinto
  • 125
  • 6

3 Answers3

5

Try this with just zip to get it in that order that you want:

[i for j in zip(alist1_temp, alist2_temp) for i in j]

if you don't mind the order just do:

alist1_temp + alist2_temp

or get it with itertools.chain thanks to @buran:

import itertools

list(itertools.chain(alist1_temp, alist2_temp))
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
1

If you like numpy way of doing this, you could use this!

np.vstack((alist1_temp,alist2_temp)).flatten('F')

or you can flatten your list comprehension as well

np.array(t).flatten()
Venkatachalam
  • 16,288
  • 9
  • 49
  • 77
1

As you specified that you want get it from from the list-comprehension:

alist1_temp=[1,4,2]
alist2_temp=[3,7,4]
L = len(alist1_temp)+len(alist2_temp)
t = [alist2_temp[i//2] if i%2 else alist1_temp[i//2] for i in range(L)]
print(t) #prints [1, 3, 4, 7, 2, 4]
Daweo
  • 31,313
  • 3
  • 12
  • 25