Kodeclik Blog


Prepending to a list in Python

Recap how you can setup a list in Python using square bracket notation:
This program prints:
Prepending to a list means adding an element to the beginning of the list. There are numerous ways to prepend to a list. Let us suppose we desire to prepend the string “Monday” to the “daylist” list.
Here are four ways:

Method 1: Use the list.insert() method

The first approach uses the list.insert() method which takes two arguments. The first argument is the position and in this case we will supply zero since we wish to prepend to the beginning of the list. The second argument is the element we wish to insert. Here is an example:
This outputs:
Note that you can only prepend one element. If you try something like:
You will get the output:
Note that the input you provided in your insert() method essentially treats the second argument (which is a list) as a single element and makes that to be the new first element of the list. Thus the moral of the story is that the insert() method takes individual elements.

Method 2: Use the list slicing operator

A second way to prepend to a list is to use the list slicing operator with 0 as both the starting and ending values of the slice. Here is how that works:
Note that in the assignment statement we give a singleton list containing ‘Monday’ (not the string ‘Monday’). This is because slicing returns a list and thus the types should match.
This will provide the same output as before:

Method 3: Create a new list with list concatenation

You can use the list concatenation operator (“+”) to prepend elements to your list. Here is how that works:
The output is:
Note several interesting aspects of this code. The original list called daylist is not modified. You can see that in the two print statements that return the same value before and after the prepending operation. Second, like the earlier method we need to provide ‘Monday’ in the form of a singleton list because the list concatenation operator (“+”) needs two lists as its arguments.

Method 4: Use deque and the appendleft() method

In this approach we use the deque (double ended queue) data structure from the collections library. We first take the given list and convert it into a deque. Then we use the appendleft() method to insert the desired element to the beginning of the deque. Then we convert the deque back to a list. Here is the code implementing this idea:
This produces the output:
There you have it - which approach is your favorite?
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2023. All rights reserved.