How do you prepend a value or item to a list? Or how do you prepend the contents of a list to another list using Python?
There are two ways to prepend items to an existing list in Python: for single items use the list method
.insert(idx, value) – this method will mutate the original list, or use the list concatenation operator
new_list + old_list which can be set to a new variable and prevent the original list being mutated.
Here are how both prepending approaches are demonstrated with Python code.
Prepend List With New Value
To prepend a list in Python with a new value, use the list method
.insert(idx, value). This method has two parameters with the first parameter being the index number where the item will be inserted, pushing everything else currently at that index and after back. The second parameter with this method is the item you want to be inserted into the list.
Here’s an example demonstrating the use of this method:
>>> my_list = [1, 2, 3] >>> my_list.insert(0, 'Here!') >>> print(my_list) ['Here!', 1, 2, 3]
Notice how the newly inserted item
'Here!' is at the front of the list, also notice that this method mutates the original list.
Another limitation of this method is that you can only insert one value at a time. If your aim is to insert an entire list as an item into the original list then this technique would work fine, however, if you want to insert the contents of a list such that more than one item is prepended to the original list then you would need to look at using a for-loop.
For example, to prepend the contents of a list into another list using the
.insert(idx, value) list method would look something like this:
>>> my_list = [1, 2, 3] >>> new_list = ['A', 'B', 'C'] >>> [my_list.insert(0, x) for x in new_list[::-1]] [None, None, None] >>> print(my_list) ['A', 'B', 'C', 1, 2, 3]
As seen in the code above I have used a list comprehension to loop through all the contents of the
new_list variable in reverse using the slice operator
[::-1] on this list. By reversing the order each time a new item is added from the list it pops it into the front of the original list – achieving the intended result of inserting the contents of the
new_list into the original list
But is there an easier way?
If you don’t want to mutate the original list then you may want to look at the next technique where you can concatenate lists together.
Prepend List Without Mutating Original List
One little issue with the list method
.insert(idx, value) is that the original list is mutated whenever this function is called. Mutations in your code can make debugging a little difficult to track, especially if mutations are happening all over your code.
Another method to prepend items to your list is to use the concatenation operator
This can be demonstrated as follows:
>>> my_list = [1, 2, 3] >>> new_value = 'A' >>> [new_value] + my_list ['A', 1, 2, 3]
Notice the value of
new_value was a simple string
'A' and that the third line above needed to be wrapped in the list brackets
[new_value]. If you forgot to do this you would have got a
TypeError like this:
>>> new_value + my_list Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "list") to str
As the error asserts the concatenation technique cannot work when you have two different types of variables being added together, therefore, they need to be converted to the same type.
You could further wrap the
new_value into an
if one-line condition to check the type will match the original list and if the
new_value is already a list it will be prepended without needing to wrap it in list brackets.
Here’s how this condition would operate:
>>> my_list = [1, 2, 3] >>> new_value = 'A' >>> (new_value if type(new_value) == list else [new_value]) + my_list ['A', 1, 2, 3] >>> new_value = ['A', 'B', 'C'] >>> (new_value if type(new_value) == list else [new_value]) + my_list ['A', 'B', 'C', 1, 2, 3]
As you can see from the code results above, the if condition (wrapped in parentheses) checks for whether the value of the
new_value can readily be inserted into the original list
my_list. If it can, then no change is needed to the
new_value variable, otherwise, if a change is needed then it is wrapped in list brackets. The last operation is then to add the result of this
if condition to the original
Lastly, you will notice with each operation that the original
my_list list doesn’t mutate. In the first example where we add the letter
'A', a new list is produced
['A', 1, 2, 3], then when the second example is run another new list is created
['A', 'B', 'C', 1, 2, 3].
This type of prepending technique permits the original list to remain intact.
To prepend an item to a list use either the
.insert(idx, value) list method or the concatenation technique. With the concatenation technique check the new value is of a list data type before prepending.