How to remove the first item from a list in Python?

by laury_ullrich , in category: Python , 2 years ago

How to remove the first item from a list in Python?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@laury_ullrich There are multiple options to remove the first element from a list in Python:

  1. You can use del to remove item from a list in Python
  2. You can use .pop() method in Python

Here is example how it works:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
cars = ["bmw", "audi", "ford"]

del cars[0]
# Output: ['audi', 'ford']
print(cars)

# OR
cars.pop(0)
# Output: ['ford']
print(cars)


Member

by violette , a year ago

@laury_ullrich 

You can remove the first item from a list in Python using the pop() method with an index of 0, like this:

1
2
my_list = [1, 2, 3, 4, 5]
my_list.pop(0)


This will remove the first item (with index 0) from the list my_list. After the pop() method is called, my_list will be [2, 3, 4, 5].


Alternatively, you can use slicing to remove the first item by creating a new list that excludes the first item, like this:

1
2
my_list = [1, 2, 3, 4, 5]
my_list = my_list[1:]


This will create a new list that starts from the second item and assigns it to my_list. After the slicing, my_list will be [2, 3, 4, 5]. Note that this method creates a new list and assigns it to the same variable, which may not be desirable if you want to modify the original list in place.