To add an element to the beginning of a Python array (also known as a list), you can use the insert()
method with an index of 0. Here is an example:
main.py86 chars4 lines
In this example, we first create an array my_list
with some elements. We then insert the value 1
at the beginning of the array using the insert()
method with index 0
. Finally, we print the updated array to verify that the new element has been added to the beginning.
Alternatively, you can also use the +
operator to concatenate a list with another list or a single element:
main.py89 chars4 lines
In this example, we create a new list [1]
and concatenate it with my_list
using the +
operator, thereby adding the element 1
to the beginning of the list.
gistlibby LogSnag