Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternately appending elements from two lists

I have three lists with elements :

a = [[0,1],[2,3],...]
b = [[5,6],[7,8],...]

c = []

I want to append elements from a and b into c to get:

c = [ [0,1],[5,6],[2,3],[7,8],.... ]
like image 328
Shivkumar kondi Avatar asked Dec 03 '25 13:12

Shivkumar kondi


2 Answers

Basic approach:

>>> a = [[0,1],[2,3]]
>>> b = [[5,6],[7,8]]
>>> c = []
>>> for pair in zip(a,b):
...   c.extend(pair)
... 
>>> c
[[0, 1], [5, 6], [2, 3], [7, 8]]
>>> 

This breaks if the lengths aren't equal. But you can deal with that case as an exercise.

like image 101
juanpa.arrivillaga Avatar answered Dec 05 '25 02:12

juanpa.arrivillaga


Another very simple approach using string slicing (and most performance efficient) as:

>>> a = [[0,1],[2,3]]
>>> b = [[5,6],[7,8]]
>>> c = a + b # create a list with size = len(a) + len(b)
>>> c[::2], c[1::2] = a, b  # alternately insert the value
>>> c
[[0, 1], [5, 6], [2, 3], [7, 8]]

Below is the comparison of results with timeit for the answers mentioned here (Python version: 2.7):

  1. Using string slicing: 0.586 usec per loop

    moin@moin-pc:~$ python -m "timeit" -s "a = [[0,1],[2,3]]; b = [[5,6],[7,8]];" "c = a + b; c[::2], c[1::2] = a, b"
    1000000 loops, best of 3: 0.586 usec per loop
    
  2. Using itertools.chain(): 1.89 usec per loop

    moin@moin-pc:~$ python -m "timeit" -s "from itertools import chain; a = [[0,1],[2,3]]; b = [[5,6],[7,8]];" "c = list(chain(*zip(a, b)))"
    1000000 loops, best of 3: 1.89 usec per loop
    
  3. Using reduce(): 0.829 usec per loop

    moin@moin-pc:~$ python -m "timeit" -s "import operator; a = [[0,1],[2,3]]; b = [[5,6],[7,8]];" "c = reduce(operator.concat, zip(a, b))"
    1000000 loops, best of 3: 0.829 usec per loop
    
  4. Using list.extend(): 0.824 usec per loop

     moin@moin-pc:~$ python -m "timeit" -s "a = [[0,1],[2,3]]; b = [[5,6],[7,8]]; c=[]" "for pair in zip(a,b): c.extend(pair)"
     1000000 loops, best of 3: 0.824 usec per loop
    
  5. Using list.append() twice: 1.04 usec per loop

    moin@moin-pc:~$ python -m "timeit" -s "a = [[0,1],[2,3]]; b = [[5,6],[7,8]]; c=[]" "for a_element, b_element in zip(a, b): c.append(a_element); c.append(b_element)"
    1000000 loops, best of 3: 1.04 usec per loop
    
like image 22
Moinuddin Quadri Avatar answered Dec 05 '25 01:12

Moinuddin Quadri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!