Use this function with a list in PYTHON. #python #programming #coding

preview_player
Показать описание
Hello Dear Coders,

In this video we will see, how we can add a new item in the existing list, at a specified index number.

So stay tuned.....
Рекомендации по теме
Комментарии
Автор

Insert is better for large lists because slices create a new list and hogs memory

seethekek
Автор

You could also do something like list[0:x] + 'b' + list[x:] to get a NEW list with b at index x. This does NOT modify the list and it returns a new list. So this might be better in some places using declarative code (Things like map and filter) since it can be chained with those operations for pretty elegant Chained one-liner expressions

sebastiangudino
Автор

Had no idea about the slicing to insert. Interesting.

Chetz
Автор

I would use pop() for each index in the list and then create a new list for each item and then merge them

opus_X
Автор

Just FYI—the slice insertion method only works with iterables, and it will add each item of that iterable separately. So my_list[2:2] = 4 will throw TypeError (int is not iterable), and my_list[2:2] = "xyz" will set my_list to ['a', 1, 'x', 'y', 'z', 2, 'c', 3] which is likely not what you were going for.

RobotModel
Автор

After 4 years of slicing, I learned that I can use it to insert a single element

knut-olaihelgesen
Автор

[This is not a list] it is an array. Not mutable.

vilijanac