-1

The function below inserts a list into another list at a specified location.

What's the best way to remove the middle brackets from the output while leaving the outer brackets on?

def insert(list1, list2, index):

    pos = 0
    new_list = []

    if index > len(list1):
        index = len(list1)
    elif index < 0:
        index = 0

    for pos in range(0, index):
        new_list.append(list1[pos])

    #for pos in range(1):
    new_list.append(list2)

    while index != len(list1):
        new_list.append(list1[index])
        index += 1

    return new_list


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

new_list = insert(list1, list2, index)
print(new_list)

Output:

['b', 'o', ['r', 'e', 'd'], 'o', 'm']
BT93
  • 329
  • 2
  • 9
  • 25

3 Answers3

1

You can simply use list slicing to get the desired results:

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

print list1[:index]+list2+list1[index:]
>>> ['b', 'o', 'r', 'e', 'd', 'o', 'm']

To break it down, list slicing works as lst[start:end] So,

list1 = ["b", "o", "o", "m"]
index = 2
print list1[:index]
>>> ['b', 'o']

print list1[index:]
>>> ['o', 'm']

So now we divided the list into two parts and then we use + operator which concatenates the lists to join the first part, list2 and second part and get in result a final list.

If you want to encapsulate the things inside a function then:

def insert(list1, list2, index):
    return  list1[:index]+list2+list1[index:]
ZdaR
  • 22,343
  • 7
  • 66
  • 87
0

Just substitute list.append() with list.extend().

def insert(list1, list2, index):

    pos = 0
    new_list = []

    if index > len(list1):
        index = len(list1)
    elif index < 0:
        index = 0

    for pos in range(0, index):
        new_list.extend(list1[pos])

    #for pos in range(1):
    new_list.extend(list2)

    while index != len(list1):
        new_list.extend(list1[index])
        index += 1

    return new_list


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

new_list = insert(list1, list2, index)
print(new_list)

Output:

['b', 'o', 'r', 'e', 'd', 'o', 'm']
alec_djinn
  • 10,104
  • 8
  • 46
  • 71
0

In your comment on the first post, you said you couldn't use extend(). Here's one way without needing it:

lists = ['b', 'o', ['r', 'e', 'd'], 'o', 'm']

new_list = []

for i in lists:
    if isinstance(i, list):
        for i2 in i:
            new_list.append(i2)
        continue

    new_list.append(i)

print(new_list)

Output:

$ python is.py 
['b', 'o', 'r', 'e', 'd', 'o', 'm']
stevieb
  • 9,065
  • 3
  • 26
  • 36