Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 599
Andersson Avatar asked May 13 '15 10:05

Andersson


People also ask

How do I add elements to a list at the end of a list?

If we want to add an element at the end of a list, we should use append . It is faster and direct. If we want to add an element somewhere within a list, we should use insert . It is the only option for this.

How do you add a string to the end of a list in Python?

Adding a string to a list inserts the string as a single element, and the element will be added to the list at the end. The list. append() will append it to the end of the list. You can refer to the below screenshot to see the output for add string to list python.


2 Answers

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] 
like image 161
EdChum Avatar answered Oct 08 '22 11:10

EdChum


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)

like image 24
Jonathan L Avatar answered Oct 08 '22 11:10

Jonathan L