Andre
Andre

Reputation: 1661

Merging List after particular element

I wanted to merge 2 lists together (ListA, ListB). But the catch is, after a certain element within the ListA.

The user enters after which element ListB should be merged with listA.

For example;

ListA = [2,1,0]
ListB = [4,5,6]

User Enters 1.

Output:

new_list = [2, 4, 5, 6, 1, 0]

Now I was thinking of using a for loop, but because of my limited knowledge in for loops I don't know how I can make the loop to stop after a certain amount of loops.

Upvotes: 0

Views: 46

Answers (3)

Kasravnd
Kasravnd

Reputation: 107287

ListA = [2,1,0]
ListB = [4,5,6]
a=[]
def merg(i):
 for i in range(i):
  a.append(ListA[i])
 for j in ListB:
  a.append(j)
 a.append(ListA[i+1])
 return a

print merg(2)

DEMO:

[2, 1, 4, 5, 6, 0]

Upvotes: 0

mgilson
mgilson

Reputation: 309919

This is actually really easy with slice assignment, as explained in the tutorial section on Lists:

ListA = [2,1,0]
ListB = [4,5,6]

# make a copy -- I'm assuming you don't want to modify ListA in the process.
new_list = ListA[:]
# insert ListB at a particular location.  I've arbitrarily chosen `1`
# basically this says to take the empty section of the list
# starting just before index 1 and ending just before index 1 and replace it
# with the contents of ListB
new_list[1:1] = ListB
# Check the output to make sure it worked.
print(new_list)  # [2, 4, 5, 6, 1, 0]

Upvotes: 4

abarnert
abarnert

Reputation: 365717

Here's a way you can do this without any mutating operations:

new_list = a[:i] + b + a[i:]

To see it in practice:

>>> a = [2, 1, 0]
>>> b = [4, 5, 6]
>>> i = 1
>>> new_list = a[:i] + b + a[i:]
>>> new_list
[2, 4, 5, 6, 1, 0]

If you don't understand any piece, you can break it down:

>>> a[:i]
[2]
>>> a[i:]
[1, 0]
>>> # etc.

So, why would you want to do this without mutating operations? Lots of possible reasons:

  • Code that doesn't mutate values is easier to reason about. It's exactly like a mathematical function; you don't have to think about the order in which things happen or the state at each step. And you can usually decompose it into simpler pieces, exactly as I did above, if you don't understand it.
  • Often you don't actually want to mutate anything. In this case, we don't have to make a copy of a in advance, because we're not going to modify it.
  • It can be more readable, or even more novice-friendly. In this case, you still have to understand slicing, but not slice assignment.
  • It's often shorter. This is a one-liner instead of a two-liner.
  • It's often more efficient. This avoids copying the entire list and then shifting most of the elements to the right.

But something it's less readable, or more verbose, or less efficient. So, it's worth knowing both ways of doing things, so you can decide which is appropriate on a case by case basis.

Upvotes: 0

Related Questions