Insert at first position of a list in Python

PythonListInsert

Python Problem Overview


How can I insert an element at the first index of a list? If I use list.insert(0, elem), does elem modify the content of the first index? Or do I have to create a new list with the first elem and then copy the old list inside this new one?

Python Solutions


Solution 1 - Python

Use insert:

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

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

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

Solution 2 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFr0z3n7View Question on Stackoverflow
Solution 1 - Pythonmichel-slmView Answer on Stackoverflow
Solution 2 - PythonAnovView Answer on Stackoverflow