0
votes

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 second to last element of list1 , followed by the second to last element of list2 , and so on (in other words the new list should consist of alternating elements of the reverse of list1 and list2 ). For example, if list1 contained [1, 2, 3] and list2 contained [4, 5, 6] , then the new list should contain [3, 6, 2, 5, 1, 4] . Associate the new list with the variable list3 .

My code:

def new(list1,list2):
    i = 0
    j = 0
    new_list = []
    for j in list1:
        new_list[i-1] = list2[j-1]
        i+= 1
        j += 1
        new_list[i-1] = list2 [j-1]
        i+= 1
        j += 1
    return new_list

I know, it's messy =_=, help?

5
This sounds a lot like homework. If it is, you should tag it as such.ChristopheD
It's not only messy; it doesn't even work -- it will blow up the first time that you try to execute new_list[i-1] = list2[j-1]. Also j is a VALUE from list1 but you then use it as a SUBSCRIPT of list2! Suggestion: use test data values of 100, 200, etc -- if you attempt to use those as list subscripts, you'll get an exception immediately, not later.John Machin

5 Answers

7
votes
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
2
votes
list(sum(zip(list1,list2)[::-1],()))
1
votes

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(_)
0
votes

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)):
0
votes

One-liner:

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

list is necessary as the prior operations return a tuple.