-2

I'm fairly new to Python, and besides finding it useful and rather easy to understand for the most part, there are still some things I'm unclear of, ergo this question.

Is it possible to insert specific sections of one list into a specific location in another list?

Say for example, I have a list called 'a', and in this list I have the numbers 1, 3 and 5 in this format:

a = [1, 3, 5]

I also have a list called 'b' which contains the numbers 2 and 4 in this format:

b = [2, 4]

My end goal would be for list 'a' to be changed to this:

a = [1, 2, 3, 4, 5]

As you can see, this would require me to specify using indices for both lists to combine them into one list in this custom format, and I am unsure as to how I could go about this.

I unintentionally left out a major detail, and that is the fact that I wanted to make use of the 'insert' function rather than 'append'.

C L
  • 11
  • 3
  • 4
    What exactly is the merging logic? Sorting the list? – Szymon Jan 26 '16 at 18:01
  • 2
    Possible duplicate of [Pythonic way to combine two lists in an alternating fashion?](http://stackoverflow.com/questions/3678869/pythonic-way-to-combine-two-lists-in-an-alternating-fashion) – F. Stephen Q Jan 26 '16 at 18:06

3 Answers3

0

Yes. Just use insert() and have the second argument be a list element.

a = [1, 3, 5]
b = [2, 4]
# The first argument is the index to insert it at.
# The second is the actual item to be inserted.
a.insert(1, b[0]) # [1, 2, 3, 5]
a.insert(3, b[1]) # [1, 2, 3, 4, 5]

Note that if you just want a sorted, you can just use this:

for item in b:
    a.append(item) # Order does not matter, we will sort it later
# a is currently [1, 3, 5, 2, 4] since append() adds to the end of the list
a.sort()
# a is now [1, 2, 3, 4, 5] as sort() re-ordered it

Or if you want it even simpler, concatenate them and then sort:

a = a + b # [1, 3, 5, 2, 4]
a.sort() # [1, 2, 3, 4, 5]

Let me know if this is unclear or not what you wanted.

ASCIIThenANSI
  • 815
  • 9
  • 25
0

How does this work for you?

a = [1,2,5,6,7]
b = [3,4]
for n,k in enumerate(a):
     if(k<b[0]):
         a = a[0:n]+b+a[n:]
         break
print(a)

using the colon to slice arrays is super useful.

kpie
  • 7,934
  • 5
  • 19
  • 40
0

If you're interleaving the lists, you can zip them using izip_longest:

>>> a = [1, 3, 5]
>>> b = [2, 4]

>>> from itertools import izip_longest

>>> [c for pair in izip_longest(a, b)
...  for c in pair if c is not None]
[1, 2, 3, 4, 5]
Peter Wood
  • 21,348
  • 4
  • 53
  • 90