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)
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.
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.
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.
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.
[value for pair in zip(a, b[::-1]) for value in pair]
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))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With