How to add element in Python to the end of list using list.insert?
Asked Answered
U

3

78

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)?

Urian answered 13/5, 2015 at 10:40 Comment(0)
A
112

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]
Aikoail answered 13/5, 2015 at 10:41 Comment(0)
H
9

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)

Hickory answered 8/11, 2019 at 1:23 Comment(0)
H
2

You can simply try this:

[1,2,3,4] + [5]

Houseraising answered 31/8, 2023 at 20:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.