Question
Asked By – ATOzTOA
I have this:
>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]
>>> print a.insert(2, 3)
None
>>> print a
[1, 2, 3, 4]
>>> b = a.insert(3, 6)
>>> print b
None
>>> print a
[1, 2, 3, 6, 4]
Is there a way I can get the updated list as the result, instead of updating the original list in place?
Now we will see solution for issue: Insert an element at a specific index in a list and return the updated list
Answer
The shortest I got: b = a[:2] + [3] + a[2:]
>>>
>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]
>>> b = a[:2] + [3] + a[2:]
>>> print a
[1, 2, 4]
>>> print b
[1, 2, 3, 4]
This question is answered By – ATOzTOA
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0