Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting list into another list using loops only:

Tags:

python-3.x

I'm using the current version of python. I need to return a copy of list1 with list2 inserted at the position indicated by index i.e if the index value is 2, list2 is inserted into list 1 at position 2. I can only use for/while loops, the range function & the list_name.append (value) methods and the lists cannot be sliced. So if list1 list1 = boom list2 = red and the index value = 2, how do I return a new list = boredom? I have this so far:

list1 = ['b','o','o','m']
list2 = ['r','e','d']
index = 2
new_list = []

if index > len(list1):
    new_list = list1 + list2
    print (new_list)
if index <= 0:
    new_list = list2 + list1
    print (new_list)
like image 381
SMF-01 Avatar asked May 30 '26 00:05

SMF-01


2 Answers

An alternative approach to Padriac's - using three for loops:

list1 = ['b','o','o','m']
list2 = ['r','e','d']

n = 2
new_list = []
for i in range(n): # append list1 until insert point
    new_list.append(list1[i])
for i in list2: # append all of list2
    new_list.append(i)
for i in range(n, len(list1)): # append the remainder of list1
    new_list.append(list1[i])
like image 186
Jon Clements Avatar answered Jun 01 '26 16:06

Jon Clements


Once you hit the index, use an inner loop to append each element from list2:

for ind, ele in enumerate(list1):
    # we are at the index'th element in list1 so start adding all
    # elements from list2
    if ind == index:
        for ele2 in list2:
            new_list.append(ele2)
    # make sure to always append list1 elements too      
    new_list.append(ele)
print(new_list)
['b', 'o', 'r', 'e', 'd', 'o', 'm']

If you must use range just replace enumerate with range:

new_list = []

for ind in range(len(list1)):
    if ind == index:
        for ele2 in list2:
            new_list.append(ele2)
    new_list.append(list1[ind])
print(new_list)
['b', 'o', 'r', 'e', 'd', 'o', 'm']

Or without ifs using extend and remove if allowed:

new_list = []
for i in range(index):
    new_list.append(list1[i])
    list1.remove(list1[i])
new_list.extend(list2)
new_list.extend(list1)

Appending as soon as we hit the index means the elements will be inserted from the correct index, the elements from list1 must always be appended after your if check.

like image 41
Padraic Cunningham Avatar answered Jun 01 '26 16:06

Padraic Cunningham