-2

I am working on some project, and it requires me to do something like this

[10, 15, 17, 18]
->
[10, 12, 15, 17, 18]

Like this, I need to put an element in between of two elements. I did try

mylist = [10, 15, 17, 18]
mylist.append(mylist[-1])
for i in range(2):
    mylist[-1 * i - 2] = mylist[-1 * i - 3]
mylist[-4] = 12

But I don't think this is efficient, and the code will probably be messy if I put this in more sophisticated codes. Is there a function to automatically do this?

3 Answers3

1

You can use the insert() method.

The usage is list.insert(index, element)

So for your program:

mylist = [10, 15, 17, 18]
mylist.insert(1, 12)

Will insert the number 12 into the index 1 of your list, which is the second place.

mohavy
  • 13
  • 2
0

Use the list.insert method:

>>> mylist = [10, 15, 17, 18]
>>> mylist.insert(1, 12)
>>> mylist
[10, 12, 15, 17, 18]

Note that from a runtime perspective this is not much more efficient than what you did, but for a list of small/fixed size the runtime efficiency aspect of this isn't really worth worrying about. (For efficient insert operations on arbitrarily large lists you probably want some kind of linked list structure rather than a standard Python list.)

Samwise
  • 68,105
  • 3
  • 30
  • 44
  • *"not much more efficient"* - Right, only about [500 times faster](https://tio.run/##ZZDRbsIwDEXf8xV@TFBBLd00NIkvQVVURsosNU5kwgNf3zkkg4lF8oN9T65vEm/pO1C/i7wsEwcPCb3DBOhj4FQ7pU5ugsB4RhpnbT4VyPG3GS9pM8bo6KRLd1h3g7mrU2BAQAIe6ez07KgiBtawrRZPG7kIK7kg2gD7f8N@UH/Zt8x025IL6eI4vaSqw64RzCiV09hnmr7CeTxd6Ssrv89rquFrQtl46Frxe5f6kNoNDyKL5at0tmuArv7oeN@3bWseVGSkpFNzX7mxlkbvrC160cyy/AA). – no comment Sep 07 '21 at 02:22
  • Both approaches are O(n). ¯\_(ツ)_/¯ You don't need to time it to figure that out. `insert` is gonna be faster by a constant factor because it's implemented on the "back end" instead of via the interpreter, but it's still rewriting the entire list to insert that one item. – Samwise Sep 07 '21 at 04:26
0

You also need to identify the position where to index, and this could be made thanks to a lambda function.

mylist = [10, 15, 17, 18]

def add_value(my_list, val):
  get_index = lambda z : next(x[0] for x in enumerate(mylist) if x[1] > z)
  ind = get_index(val)
  return my_list.insert(ind, val)

print(add_value(mylist, 12))
Christophe
  • 651
  • 4
  • 22