How to add element in Python to the end of list using list.insert?
147,435
Solution 1
You'll have to pass the new ordinal position to insert
using len
in this case:
In [62]:
a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]
Solution 2
list.insert with any index >= len(of_the_list) places the value at the end of list. It behaves like append
Python 3.7.4
>>>lst=[10,20,30]
>>>lst.insert(len(lst), 101)
>>>lst
[10, 20, 30, 101]
>>>lst.insert(len(lst)+50, 202)
>>>lst
[10, 20, 30, 101, 202]
Time complexity, append O(1), insert O(n)
Comments
-
Andersson almost 2 years
There is a list, for example,
a=[1,2,3,4]
I can use
a.append(some_value)
to add element at the end of list, and
a.insert(exact_position, some_value)
to insert element on any other position in list but not at the end as
a.insert(-1, 5)
will return [1,2,3,5,4]. So how to add an element to the end of list using list.insert(position, value)?
-
David Donari almost 5 yearsAlso, using a.insert(-len(a),5) you can insert the element at the beginning lol
-
Flux over 4 yearsIf not mistaken, O(n) time complexity for
insert
is only valid for the average case. Inserting at the end of the list probably has the same cost as appending. -
Kelly Bang about 4 yearsOr you know, just an a.insert(0, 5) to save you a len lookup
-
Lohmar ASHAR over 2 years... this pointed me to the less obvious option ... for my situation ... that is: just use
.append
:D, might not apply to everyone's situation -
alper over 2 yearsDoes is behave same as
append()
in the background?