3

"Given the lists list1 and list2 that are of the same length, create a new list consisting of the first element of list1 followed by the first element of list2, followed by the second element of list1, followed by the second element of list2, and so on (in other words the new list should consist of alternating elements of list1 and list2). For example, if list1 contained [1, 2, 3] and list2 contained [4, 5, 6], then the new list should contain [1, 4, 2, 5, 3, 6]. Associate the new list with the variable list3."

    list1 = []
    list2 = []
    list3 = []
    for i in range(len(list3)):
        list3.append(list1)
        list3.append(list2)

I'm pretty sure this is dead wrong. What should I improve? By the way, I believe this must include both len and range.

Donavan Allen
  • 31
  • 1
  • 1
  • 4

4 Answers4

5

I would do it with a list comprehension, rather than anything with len or range. e.g.:

>>> list1 = [1, 2, 3]
>>> list2 = ['a', 'b', 'c']
>>> zip(list1, list2)
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> [x for pair in zip(list1, list2) for x in pair]
[1, 'a', 2, 'b', 3, 'c']
wim
  • 338,267
  • 99
  • 616
  • 750
5
>>> from itertools import chain
>>> list1 = [1, 2, 3]
>>> list2 = [4, 5, 6]
>>> list(chain.from_iterable(zip(list1, list2)))
[1, 4, 2, 5, 3, 6]
jamylak
  • 128,818
  • 30
  • 231
  • 230
2
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = []

for x1, x2 in zip(list1, list2):
    list3.extend([x1, x2])
Yarkee
  • 9,086
  • 5
  • 28
  • 29
0

Please look at the following snippet, maybe it will help

>>> list1 = [1,2,3]
>>> list2 = [4,5,6]
>>> list3 = []
>>> for i in range(len(list1)):
...     list3.append(list1[i])
...     list3.append(list2[i])
...
>>> list3
[1, 4, 2, 5, 3, 6]
Sidharth Shah
  • 1,569
  • 1
  • 11
  • 14