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?
Asked
Active
Viewed 4.1e+01k times
226

geekTechnique
- 850
- 1
- 11
- 38

Fr0z3n7
- 2,548
- 2
- 14
- 15
-
1It's a duplicate of [What's the idiomatic syntax for prepending to a short python list?](https://stackoverflow.com/q/8537916/2745495). – Gino Mempin Jan 19 '21 at 00:31
2 Answers
418
Use insert
:
In [1]: ls = [1,2,3]
In [2]: ls.insert(0, "new")
In [3]: ls
Out[3]: ['new', 1, 2, 3]

meetar
- 7,443
- 8
- 42
- 73

michel-slm
- 9,438
- 3
- 32
- 31
37
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