Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert at first position of a list in Python [closed]

People also ask

How do you add an item to a list in Python in the first position?

Use the + Operator to Append an Element to the Front of a List in Python. Another approach to append an element to the front of a list is to use the + operator. Using the + operator on two or more lists combines them in the specified order.

How do I add a list to a specific position?

You can add an item to a list with the append() method. A new item is added at the end. If you want to add to other positions, such as the beginning, use the insert() method described later. A list is also added as one item, not combined.

How do you move an item to the front of a list in Python?

insert() To prepend to a list in Python, use the list. insert() method with index set to 0, which adds an element at the beginning of the list. The insert() is a built-in Python function that inserts an item to the list at the given index.


Use insert:

In [1]: ls = [1,2,3]

In [2]: ls.insert(0, "new")

In [3]: ls
Out[3]: ['new', 1, 2, 3]

From the documentation:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a),x) is equivalent to a.append(x)

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists