tags:

views:

139

answers:

5

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?

A: 

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)):
Amber
I don't want to go manually through both lists and add the values, I want to add from two pre-existing lists, thanks anyway.
Alex
But see, the `append()` method can take anything as it's argument... including an element of an existing list. Such as, say... `new_list.append(list1[i]))` or similar.
Amber
+5  A: 
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
ChristopheD
A: 

One-liner:

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

list is necessary as the prior operations return a tuple.

int3
Golfed for fun: `sum(map(list,reversed(zip(list1,list2))),[])`
jleedev
mm thanks for giving me the idea of passing `list()` to `reduce()`, instead of vice versa. Makes for less nesting.
int3
+1  A: 
list(sum(zip(list1,list2)[::-1],()))
gnibbler
+1  A: 

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(_)
Nick D