2

So I'm trying to append list value to another one by turns. This is my code:

lis1 = [1, 2, 3, 4, 5]
lis2 = [6, 7, 8, 9, 10]
for i, value in enumerate(lis2):
  lis1.append(i)
print(lis1)

My expected output is [1, 6, 2, 7, 3, 8, 4, 9, 5, 10]

But what I got is [1, 2, 3, 4, 5, 0, 1, 2, 3, 4]

Any help would be appreciated

Yoel Regen
  • 81
  • 1
  • 11

3 Answers3

2

You want to use zip for this. That generates a list of tuples, and to flatten that you can use itertools.chain:

import itertools

list(zip(lis1, lis2))
# [(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]

list(itertools.chain(*zip(lis1, lis2)))
# [1, 6, 2, 7, 3, 8, 4, 9, 5, 10]

# or:
list(itertools.chain.from_iterable(zip(lis1, lis2)))
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
1

You could do it like this:

out = []
for x in range(len(lis1)):
    out.append(lis1[x])
    out.append(lis2[x])

Output

[1, 6, 2, 7, 3, 8, 4, 9, 5, 10]
Sebastien D
  • 4,369
  • 4
  • 18
  • 46
1

If you don't want to use zip from itertools, you can use list.extend() as followings:

lis1 = [1, 2, 3, 4, 5]
lis2 = [6, 7, 8, 9, 10]
new_list = []

for index, value in enumerate(lis1):
  new_list.extend((lis1[index],lis2[index]))

print(new_list)
Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35