2

I want to combine two lists in an alternating way in Python.

list1 = ['A']
list2 = [1, 2, 3, 4]

What I've tried:

combination = [x for y in zip(list1, list2) for x in y]
# Output: 
['A', 1]

# Expected output:
['A', 1, 'A', 2, 'A', 3, 'A', 4]

How can I combine these two lists and get the expected output? (Preferably list comprehension)

pmqs
  • 3,066
  • 2
  • 13
  • 22

2 Answers2

2

One way is to use itertools cycle function:

from itertools import cycle

list1 = ['A']
list2 = [1, 2, 3, 4]

combination = [x for y in zip(cycle(list1), list2) for x in y]

This also works with

list1 = ['A', 'B']
loocars
  • 46
  • 2
  • Could also use `itertools.chain.from_iterable` which is basically `flatten`, rather than a list comprehension. Also OP if the input doesn't have to be a list, you can just use `itertools.repeat` to create an infinite iterator of a single item. – Masklinn Jan 25 '23 at 10:50
  • @Masklinn True but OP specifically wants to use a list comprehension – DarkKnight Jan 25 '23 at 10:52
1

list1*len(list2) will repeat the first list elements as many times as the length of the second list.

combination = [x for y in zip(list1*len(list2), list2) for x in y]

['A', 1, 'A', 2, 'A', 3, 'A', 4]
Jamiu S.
  • 5,257
  • 5
  • 12
  • 34