add an element to the beginning of an array in python

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.py
my_list = [2, 3, 4, 5]
my_list.insert(0, 1)
print(my_list)  # Output: [1, 2, 3, 4, 5]
86 chars
4 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.py
my_list = [2, 3, 4, 5]
my_list = [1] + my_list
print(my_list)  # Output: [1, 2, 3, 4, 5]
89 chars
4 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