Reputation: 1661
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
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
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
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:
a
in advance, because we're not going to modify it.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