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.
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.
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, soa.insert(0, x)
inserts at the front of the list, anda.insert(len(a),x)
is equivalent toa.append(x)
http://docs.python.org/2/tutorial/datastructures.html#more-on-lists
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With