1

I have a list like this:

["*****", "*****"]

I want to insert the elements of another list to the middle of this list like this:

["*****", "abc", "ded", "*****"]

However, my attempt produces a list nested inside another list:

["*****", ["abc", "ded"], "*****"]

This is my code:

def addBorder(picture):

    length_of_element = len(picture[0])
    number_of_asterisks = length_of_element + 2
    new_list = ['*' * number_of_asterisks for i in range(0, 2)]
    new_list.insert(len(new_list)//2, [value for value in picture])
    
    return new_list

I know that my code is good. I just want to know what tweaks I need to make.

martineau
  • 112,593
  • 23
  • 157
  • 280
oo92
  • 2,594
  • 2
  • 19
  • 49
  • No its not a duplicate. I don't have trouble understanding slicing notation. I want to append the elements of a list and not the entire list to the middle of another list. – oo92 Aug 17 '20 at 05:27
  • 1
    Insert inserts ONE element at a position - not multiple. Slice the list: `newlist = oldlist[:half] + data + newlist[half:]` – Patrick Artner Aug 17 '20 at 05:27
  • Yea but `data` would do the exact same thing. It would just add it as a list and not as individual elements. – oo92 Aug 17 '20 at 05:28
  • 2
    list.insert() can't be used the way you want. You can insert all single elements in a loop - or slice the list. The dupe is the way to do it. – Patrick Artner Aug 17 '20 at 05:29

1 Answers1

3
a = ['****', '****']
b = ['abc', 'efg']
mid_index = len(a)//2 # Integer result for a division

result = a[:mid_index] + b + a[mid_index:]

If you want to assign the result to a directly, You can also simply:

a[mid_index:mid_index] = b
Patrick Artner
  • 48,339
  • 8
  • 43
  • 63
Or Y
  • 1,923
  • 1
  • 15