Append Item to Front of List in Python

Append Item to Front of List in Python

It's a fairly common occurance to append an item to the end of a list, but what if you need to add an item to the front of the list? There are a number of ways to achieve this in Python.

Insert

Python lists have an insert() method, which allows you to insert an item at a specific index. In our case, we want to insert the item at the very beginning, which is index 0. To achieve this with insert(), we can use the following code:

>>> my_list = [2, 3, 4]
>>> my_list.insert(0, 1)
>>> my_list
[1, 2, 3, 4]

By specifying the index 0, we are inserting the item at the beginning of the list.

Combining Lists

The Python language allows objects, like lists, to override math operators, like the addition operator +. This allows you to combine two lists together, and create a new list with the combined values. We can use this to our advantage and create a new list that has our item at the front.

Note that I said we need to combine two lists, not a value and a list. This means we'll need to wrap the value in brackets first, and then perform the addition:

>>> my_list = [2, 3, 4]
>>> my_list = [1] + my_list
>>> my_list
[1, 2, 3, 4]

Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

By wrapping our value in brackets, we turn it into a one-element list, which can then be added to my_list.

A similar approach can be used to place our value at the front of the list, but without needing to wrap it in brackets. This can be achieved by using the unpacking operator, *.

The unpacking operator requires Python 3.x and will not work in Python 2.

The unpacking operator is used to unpack a list into individual elements. This allows you to create a new list with the individual elements of the original list. Using our use-case as an example, let's see how we can add our value to the front of our list.

>>> my_list = [2, 3, 4]
>>> my_list = [1, *my_list]
>>> my_list
[1, 2, 3, 4]

Notice how we didn't need to wrap our value in brackets, but instead we created a new list where the elements were our value and the unpacked values of my_list.

Last Updated: July 1st, 2022
Was this helpful?
Project

Real-Time Road Sign Detection with YOLOv5

# python# machine learning# computer vision# pytorch

If you drive - there's a chance you enjoy cruising down the road. A responsible driver pays attention to the road signs, and adjusts their...

David Landup
David Landup
Details
Project

Data Visualization in Python: The Collatz Conjecture

# python# matplotlib# data visualization

The Collatz Conjecture is a notorious conjecture in mathematics. A conjecture is a conclusion based on existing evidence - however, a conjecture cannot be proven....

David Landup
Jovana Ninkovic
Details

© 2013-2022 Stack Abuse. All rights reserved.

DisclosurePrivacyTerms