Mojo Jojo
Mojo Jojo

Reputation: 39

Adding elements of one list to specific places in another list: Python

Pretty much all questions I saw re: this problem were more about concatenation or doing something like adding spaces between elements in a list.

Suppose I had:

a = [1, 3, 5, 7, 9]
b = [2, 4, 6, 8, 10]

I'd like for an element in b to be appended after each element in a, so that I would end up with c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. How would I go about this?

Upvotes: 2

Views: 197

Answers (4)

abhilash_goyal
abhilash_goyal

Reputation: 701

May be this could help ...

def alternateListInsert(a,b):
    fIndex = 1
    for i in range(len(b)):
        a.insert(fIndex,b[i]);
        fIndex += 2

    return a

Upvotes: 1

ninge
ninge

Reputation: 1598

c = [] 
for i in range(len(a)):
   c.append(a[i])
   c.append(b[i])

This would require a to be the same length as b. You would have to add to this slightly if they were different, but it would be the same idea.

If your goal was just wanting to get a sorted list of both a and b...

c = sorted(list(set().union(a, b)))

Upvotes: 3

Gavin Achtemeier
Gavin Achtemeier

Reputation: 325

Looping with an insert() works and is relatively straightforward:

for i in range(len(a)):
    a.insert(2*(i)+1, b[i])

note list.insert() needs to move every subsequent list entry back one position in memory which is quite inefficient for large lists, a deque (think doubly linked list) from collections.deque may be a better choice.

If you are trying to allocate a new list:

c = []
for i in range(len(a)):
    c.append(a[i])
    c.append(b[i])

Also notice that this specific implementation only works for lists of equal length.

Upvotes: 2

AChampion
AChampion

Reputation: 30268

There is a roundrobin recipe in itertools but that is a bit overkill for your example but does work with unequal lengths.
For equal length sublists then all you need to do is zip() and flatten:

>>> [n for p in zip(a, b) for n in p]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Or using itertools.chain.from_iterable:

>>> import itertools as it
>>> list(it.chain.from_iterable(zip(a, b)))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Alternatively, you can write your own generator:

def gen(a, b):
    for x, y in zip(a, b):
        yield x
        yield y

>>> list(gen(a, b))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Upvotes: 2

Related Questions