Skip to content Skip to sidebar Skip to footer

Creating New List With Values From Two Prior Lists

Given the lists list1 and list2 that are of the same length, create a new list consisting of the last element of list1 followed by the last element of list2 , followed by the s

Solution 1:

l1 = [1,2,3]
l2 = [4,5,6]

newl = []
for item1, item2 in zip(reversed(l1), reversed(l2)):
    newl.append(item1)
    newl.append(item2)

print newl

Solution 2:

list(sum(zip(list1,list2)[::-1],()))

Solution 3:

Yet another way,

from itertools import izip
l1 = [1, 2, 3, 4]
l2 = [5, 6, 7, 8]
l = []
for _ in izip(reversed(l1), reversed(l2)): l.extend(_)

Solution 4:

May I suggest making your job much simpler by using the list .append() method instead?

>>> mylist = []
>>> mylist.append(1)
>>> mylist
[1]
>>> mylist.append(7)
>>> mylist
[1, 7]

Also another small suggestion, instead of iterating over one list or the other, I'd suggest iterating over numerical indices:

for i in range(len(list1)):

Solution 5:

One-liner:

reduce(lambda x,y: list(x+y), reversed(zip(list1,list2)))

list is necessary as the prior operations return a tuple.


Post a Comment for "Creating New List With Values From Two Prior Lists"