Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new list by taking first item from first list, and last item from second list

How do I loop through my 2 lists so that I can use

a=[1,2,3,8,12]
b=[2,6,4,5,6]

to get

[1,6,2,5,3,8,6,12,2]

OR use

d=[a,b,c,d]
e=[w,x,y,z]

to get

[a,z,b,y,c,x,d,w]

(1st element from 1st list, last element from 2nd list)
(2nd element from 1st list, 2nd to last element from 2nd list)

like image 555
XXXX Avatar asked Mar 04 '16 13:03

XXXX


People also ask

How do I add an item to a list from another list?

You can use the extend() method to add another list to a list, i.e., combine lists. All items are added to the end of the original list. You may specify other iterable objects, such as tuple . In the case of a string ( str ), each character is added one by one.

How do you get the first element from each nested list of a list?

Approach #2 : Using zip and unpacking(*) operator This method uses zip with * or unpacking operator which passes all the items inside the 'lst' as arguments to zip function. Thus, all the first element will become the first tuple of the zipped list. Returning the 0th element will thus, solve the purpose.

How do you return the first and last element in a list Python?

List slicing is another method in which we directly refer to the positions of elements using the slicing technique using colons. The first element is accessed by using blank value before the first colon and the last element is accessed by specifying the len() with -1 as the input.

Which list method adds a new item to the end of a list?

append() and . extend() methods to add elements to a list. You can add elements to a list using the append method. The append() method adds a single element towards the end of a list.


2 Answers

[value for pair in zip(a, b[::-1]) for value in pair]
like image 192
Phu Ngo Avatar answered Oct 17 '22 09:10

Phu Ngo


You can zip the first list with the reverse of second one (using itertools.izip_longest) then join the columns using itertools.chain:

>>> d=['a','b','c','d']
>>> e=['w','x','y','z']
>>> 
>>> from itertools import chain, zip_longest # in python 2 use izip_longest
>>> 
>>> list(chain(*izip_longest(d, e[::-1])))
['a', 'z', 'b', 'y', 'c', 'x', 'd', 'w']

The advantage of using zip_longest() is that it takes a fillvalue argument which will be passed to fill the omitted items when the length of your lists are not equal.

If you are sure that the length of the lists are equal you better to use built-in function zip().

>>> d=['a','b']
>>> e=['w','x','y','z']
>>> list(chain(*izip_longest(d, e[::-1], fillvalue='')))
['a', 'z', 'b', 'y', '', 'x', '', 'w']

More pythonic way suggested by @Jon Clements:

list(chain.from_iterable(zip_longest(d, reversed(e))))
like image 42
Mazdak Avatar answered Oct 17 '22 08:10

Mazdak