2

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?

4 Answers 4

3
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)))
Sign up to request clarification or add additional context in comments.

Comments

2

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]

3 Comments

I like the idea of a generator but zip() allocates a list which kind of defeats the purpose
@minitotent zip() doesn't allocate a list in Py3, it is equivalent to itertools.izip() in Py2.
oh my bad, I looked up the python2 version, +1 for a relevant generator
2

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.