user11064812
user11064812

Reputation:

How do I combine the lists in the order I want?

How do I combine the lists in the order I want?

I have 3 lists. I want to add the elements of these lists to the new list one by one.

example: sample lists I have

list1 = ["a", "b", "z", "k"]
list2 = ["w", "5", "1", "6"]
list3 = ["gt", "ty", "67", "l"]

the order i want

new_list = [list1,list2,list3,list1,list2,list3,list1,list2,list3] like this

or like this

new_list = [a,w,gt,b,5,ty] 

How can I create this list with python

Upvotes: 0

Views: 60

Answers (3)

wasif
wasif

Reputation: 15478

Try this:

newList = []
for x,y,z in zip(list1,list2,list3):
  newList.extend((x,y,z))

Upvotes: 0

Charles Averill
Charles Averill

Reputation: 183

Popping should work for the second list output you want, although it doesn't match up with the first:

new_list = []

while list1 or list2 or list3:
    if list1:
        new_list.append(list1.pop(0))
    if list2:
        new_list.append(list2.pop(0))
    if list3:
        new_list.append(list3.pop(0))

Upvotes: 0

baduker
baduker

Reputation: 20042

You can try this:

import itertools

list1 = ["a", "b", "z", "k"]
list2 = ["w", "5", "1", "6"]
list3 = ["gt", "ty", "67", "l"]


print(list(itertools.chain(*zip(list1, list2, list3))))

Output: ['a', 'w', 'gt', 'b', '5', 'ty', 'z', '1', '67', 'k', '6', 'l']

Upvotes: 1

Related Questions