Python (Scripting) - Append values to the beginning of a list

by
Jeremy Canfield |
Updated: June 22 2024
| Python (Scripting) articles
By default, Python appends new values to the end of a list. Check out my article FreeKB - Python (Scripting) - Append values to the end of a list.
insert can be used to append new values to the beginning of a list. The 0 here means to insert the new image at index 0, the beginning.
#!/usr/bin/python3
fruits = []
print(f"fruits before insert = {fruits}")
fruits.insert(0, "apple")
fruits.insert(0, "banana")
fruits.insert(0, "orange")
fruits.insert(0, "grapes")
print(f"fruits after insert = {fruits}")
Running this script should output the following.
fruits before insert = []
fruits after insert = ['grapes', 'orange', 'banana', 'apple']
Did you find this article helpful?
If so, consider buying me a coffee over at