Last modified: Jan 10, 2023 By Alexander Williams
Python List: insert at index 0
To insert an item in a list at index 0, we have two options:
- Using the insert() method
- Using the + operator
Insert at index 0 using the insert() method
insert() is a method that inserts an item in a list at a given position.
insert() Syntax
list.insert(index, item)
insert() accept two required parameters:
- index: Position to insert the item
- item: Item value
insert() Example
In the following example, we'll insert the "HTML" value at the index 0 of my_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 you can see, the "HTML" has been inserted at index 0.
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.
+ operator Syntax
[item to insert] + my_list
+ operator Example
In the following example, we'll use the + operator to insert "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:
- Convert the "HTML" string to a list using the list brackets []
- Merge two lists using the + operator.
We can also use the + operator to insert multi items at the front of a list. Let's see an example.
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 </>