Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the idiomatic syntax for prepending to a short python list?

list.append() is the obvious choice for adding to the end of a list. Here's a reasonable explanation for the missing list.prepend(). Assuming my list is short and performance concerns are negligible, is

list.insert(0, x) 

or

list[0:0] = [x] 

idiomatic?

like image 808
hurrymaplelad Avatar asked Dec 16 '11 17:12

hurrymaplelad


People also ask

Can you prepend to a list in Python?

While Python has a method to append values to the end of a list, there is no prepend method. By the end of this tutorial, you'll have learned how to use the . insert() method and how to concatenate two lists to prepend. You'll also learn how to use the deque object to insert values at the front of a list.

How do you add zeros to a list in Python?

Solution: Use the list. insert(0, x) element to insert the element x at the first position 0 in the list.


2 Answers

The s.insert(0, x) form is the most common.

Whenever you see it though, it may be time to consider using a collections.deque instead of a list. Prepending to a deque runs in constant time. Prepending to a list runs in linear time.

like image 147
Raymond Hettinger Avatar answered Sep 22 '22 09:09

Raymond Hettinger


If you can go the functional way, the following is pretty clear

new_list = [x] + your_list 

Of course you haven't inserted x into your_list, rather you have created a new list with x preprended to it.

like image 33
Nil Geisweiller Avatar answered Sep 22 '22 09:09

Nil Geisweiller