Last modified: Jun 17, 2023 By Alexander Williams
2 Methods to Insert Item at Index 0 of List Python
This article focuses on inserting an item at index 0 in a Python list. To insert, we'll use:
- insert() method
- + operator method
Insert at index 0 using the insert() method
The insert() function inserts an item in a list at a specified index. We can use this function to insert an item at index 0.
In the following example, we will insert the value "HTML" at index 0 of the my_list
list.
my_list = ["Python", "Django", "Javascript"] # 👉️ List
new_list = my_list.insert(0, "HTML") # 👉️ Insert at index 0
print(my_list) # 👉️ Print
Output:
['HTML', 'Python', 'Django', 'Javascript']
As observed, the value "HTML" has been successfully inserted at index 0 of the my_list list.
Insert at index 0 using the + operator
We can also use the + operator to insert at index 0. With the + operator, we can insert one item or more in the front of a list.
The example below will utilize the + operator to insert the value "HTML" at index 0:
my_list = ["Python", "Django", "Javascript"] # 👉️ List
new_list = ["HTML"] + my_list # 👉️ Megre ["HTML"] with my_list
print(new_list) # 👉️ Print
Output:
['HTML', 'Python', 'Django', 'Javascript']
What we did:
- Converted the string "HTML" into a list using the list brackets [].
- Merged the two lists using the + operator.
To insert multiple items at index 0 of a list, follow the example below:
my_list = ["Python", "Django", "Javascript"] # 👉️ List
list_to_insert = [1, 2, 3, 4] # 👉️ List to Insert
new_list = list_to_insert + my_list # 👉️ Megre list_to_insert with my_list
print(new_list) # 👉️ Print
Output:
[1, 2, 3, 4, 'Python', 'Django', 'Javascript']
Here, we have inserted multi numbers at the front of my_list. You can visit Append Multiple Items to List in Python for more information about inserting multi items.
Conclusion
This tutorial taught us how to insert an item in a list at index 0. For more tutorials about List, scroll down you will find it.
Happy Coddind </>