To add a value at the first position (index 0) of a list in Python, we can use the insert method of a list object. Here is an example code snippet:
main.py59 chars4 lines
Output:
main.py16 chars2 lines
In the above code, we first initialize a list my_list
with some values [2, 3, 4, 5]
. Then, we call the insert
method on this list and pass two arguments: the index where we want to insert the value (in this case, 0 for the first position), and the value we want to insert (in this case, 1). This inserts the value 1 at the beginning of the list. Finally, we print the updated list to the console to verify the changes.
gistlibby LogSnag