Python pop first element from list

How to remove the first element from a list in Python

In this Python tutorial, we will see how to remove the first element from a list in Python using different methods with practical examples.

In Python, a list is a mutable (changeable) collection of items. Each item, or element, can be of any data type. They are enclosed within square brackets, and each item is separated by a comma. For example:

states = ["California", "Texas", "Florida", "New York", "Illinois"]

Here, we have a Python list of five U.S. states. Sometimes, we may want to remove the first element from this list.

Remove the first element from a list in Python

There are several ways to accomplish this, which we will detail below:

  • del statement
  • pop() method
  • List slicing
  • remove() method
  • List comprehension

we will see them one by one using demonstrative examples.

Method-1: remove the first element of a Python list using the del statement

One of the most straightforward methods to remove the first element from a Python list is to use the del statement in Python. The del statement deletes an element at a specific index.

Note: In Python, list positive indexing starts from 0.

For example, we have a list of the first five U.S. Presidents: Let’s try to remove the ‘Washington’ from the list.

presidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe"] del presidents[0] print(presidents)

The output is: After this operation, “Washington” is removed from the list.

['Adams', 'Jefferson', 'Madison', 'Monroe']

How to remove the first element of the Python list using del statement

This way we can use the del statement to remove the first element of the Python list.

Method-2: Remove the first element of the Python list using the pop() method

The pop() method is another way to remove an element from a list in Python. By default, pop() removes and returns the last element from the list. However, we can also specify the index of the element to be removed. So, here we will use the index number of the first element to remove it.

For example, Consider a list of popular American sports:

sports = ["Football", "Basketball", "Baseball", "Hockey", "Soccer"] removed_sport = sports.pop(0) print(sports)

The output is: In this case, “Football” is removed from the list.

['Basketball', 'Baseball', 'Hockey', 'Soccer']

How to remove the first element of the Python list using pop method

This way we can use the pop() method to remove the first element from a Python list.

Читайте также:  Php centos not working

Method-3: Remove the first element from a Python list using List slicing

List slicing is a method in Python list to extract a part of a list. This technique can also be used to remove the first element from a Python list. The list slicing includes the start point and excludes the stop point.

For example, Let’s take the largest cities in the U.S. by population. So, here we have mentioned the start point for list slicing(it is included) but the stop point is not mentioned so it will go till the last of the list:

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"] cities = cities[1:] print(cities)

The output is: Here as we are using the same variable name for the result. so, the result will overwrite the previously stored data. This will create a new list without “New York” with the same name.

['Los Angeles', 'Chicago', 'Houston', 'Phoenix']

How to remove the first element of the Python list using list slicing

This way we use list slicing to remove the first element of the Python list.

Method-4: Remove the first element of the Python list using the remove() method

The remove() method in Python removes the first occurrence of a specified value from a list. However, we must know the actual value that we want to remove, not just its position. If we want to remove the first element of the Python list.

For example, If we have a list of the Great Lakes:

lakes = ["Superior", "Michigan", "Huron", "Erie", "Ontario"] lakes.remove("Superior") print(lakes)

The output is: After this operation, “Superior” is removed from the list.

['Michigan', 'Huron', 'Erie', 'Ontario']

How to remove the first element of the Python list using remove method

This way we can use the remove() method to remove the first element of the Python list.

Method-5: Remove the first element of the Python List using List comprehension

List comprehension provides a concise way to create or modify lists in Python. It can be utilized to remove the first element of a list. In this, we’ll be creating a new list in Python that includes every element from the list except for the first one.

For example, We have a list of the top five U.S. universities:

universities = ["MIT", "Stanford", "Harvard", "Caltech", "Chicago"] universities = [universities[i] for i in range(1, len(universities))] print(universities)

The output is: Here as we are using the same variable name for the result. so, the result will overwrite the previously stored data. This will create a new list without “MIT” with the same name.

['Stanford', 'Harvard', 'Caltech', 'Chicago']

How to remove the first element of the Python list using list comprehension

This way we can use the list comprehension to remove the first element of the Python list.

Note: we can use negative index numbers also.

Conclusion:

In conclusion, Removing the first element from a list in Python can be accomplished using several methods, including the del statement, the pop() method, list slicing, the remove() method, and list comprehension. The method we choose to use depends on our specific needs and the context in which we’re working.

Читайте также:  Какие border в html

You may also like to read:

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Как удалить элемент из списка в Python

Рассказываем, как работают методы remove(), pop(), clear() и ключевое слово del.

Иллюстрация: Оля Ежак для Skillbox Media

Иван Стуков

В Python есть много удобных механизмов для работы со списками. И удалять элементы из них можно по-разному.

4 главных способа удалить элемент из списка

В этой статье мы рассмотрим четыре основных метода. Их функциональность в некоторых случаях пересекается, поэтому иногда они вполне взаимозаменяемы.

Метод remove(): удаление по значению

remove() можно использовать, когда мы точно знаем значение, от которого хотим избавиться. В качестве аргумента remove() получает объект, находит совпадение и удаляет его, ничего не возвращая:

new_list = ['ноль', 1, [2.1, 'два и два'], 3, 'IV'] new_list.remove(1) print(new_list ) >>> ['ноль', [2.1, 'два и два'], 3, 'IV']

Можно удалять и более сложные объекты: например, внутренние списки. Главное — в точности передать этот объект методу:

new_list = ['ноль', 1, [2.1, 'два и два'], 3, 'IV'] new_list.remove([2.1, 'два и два']) print(new_list) >>> ['ноль', 1, 3, 'IV']

remove() удаляет только первое совпадение с искомым элементом. Например, так он себя поведёт, если в списке будет несколько строк ‘ноль’:

change_list = ['ноль', 1, [2.1, 'два и два'], 'ноль', 3, 'IV'] change_list.remove('ноль') print(change_list) >>> [1, [2.1, 'два и два'], 'ноль', 3, 'IV']

При попытке удалить значение, которого нет в списке, Python выдаст ошибку ValueError.

Метод pop(): удаление по индексу

pop() подойдёт, когда известно точное местоположение удаляемого элемента. В качестве аргумента pop() получает индекс, а возвращает удалённое значение:

new_list = ['ноль', 1, [2.1, 'два и два'], 3, 'IV'] new_list.pop(2) >>> [2.1, 'два и два'] print(new_list) >>> ['ноль', 1, 3, 'IV']

Если передать отрицательное значение, то pop() будет считать индексы не с нуля, а с -1:

new_list = ['ноль', 1, [2.1, 'два и два'], 3, 'IV'] new_list.pop(-2) print(new_list) #Удалили предпоследний элемент. >>> ['ноль', 1, [2.1, 'два и два'], 'IV']

А вот если оставить pop() без аргумента, то удалится последний элемент — потому что -1 является аргументом по умолчанию:

new_list = ['ноль', 1, [2.1, 'два и два'], 3, 'IV'] new_list.pop() print(new_list) >>> ['ноль', 1, [2.1, 'два и два'], 3]

При попытке обратиться в методе pop() к несуществующему индексу, интерпретатор выбросит исключение IndexError.

Метод clear(): очищение списка

clear() удаляет из списка всё, то есть буквально очищает его. Он не принимает аргументов и не возвращает никаких значений:

new_list = ['ноль', 1, [2.1, 'два и два'], 3, 'IV'] new_list.clear() print(new_list) >>> []

Ключевое слово del: удаление срезов

del, как и метод pop(), удаляет элементы списка по индексу. При этом с его помощью можно избавиться как от единичного объекта, так и от целого среза:

new_list = ['ноль', 1, [2.1, 'два и два'], 3, 'IV'] del new_list[2] print(new_list) >>> ['ноль', 1, 3, 'IV']

Если передать срез, то элемент с правым индексом не удалится. В примере ниже это строка ‘IV’:

new_list = ['ноль', 1, [2.1, 'два и два'], 3, 'IV'] del new_list[1:4] print(new_list) >>> ['ноль', 'IV']

Чтобы очистить список, достаточно передать полный срез [:]:

new_list = ['ноль', 1, [2.1, 'два и два'], 3, 'IV'] del new_list[:] print(new_list) >>> []

Также del можно использовать с отрицательными индексами:

new_list = ['ноль', 1, [2.1, 'два и два'], 3, 'IV'] del new_list[-4] print(new_list) >>> ['ноль', [2.1, 'два и два'], 3, 'IV']

Со срезами это тоже работает:

new_list = ['ноль', 1, [2.1, 'два и два'], 3, 'IV'] del new_list[-3:-1] print(new_list) >>> ['ноль', 1, 'IV']

Если при удалении единичного элемента указать несуществующий индекс, то Python выдаст ошибку IndexError.

Как удалить первый элемент списка в Python

Довольно часто, например, при реализации стека, нужно удалить первый элемент списка. Возьмём наш new_list и посмотрим, какими способами это можно сделать.

Читайте также:  Html form radio text

С помощью метода pop(0)

Передаём в качестве аргумента pop() индекс 0:

new_list = ['ноль', 1, [2.1, 'два и два'], 3, 'IV'] new_list.pop(0) print(new_list) >>> [1, [2.1, 'два и два'], 3, 'IV']

С помощью ключевого слова del

Используем del с элементом с индексом 0.

new_list = ['ноль', 1, [2.1, 'два и два'], 3, 'IV'] del new_list[0] print(new_list) >>> [1, [2.1, 'два и два'], 3, 'IV']

Как удалить несколько элементов

Если элементы, от которых нужно избавиться, находятся по соседству друг с другом, то удобнее всего использовать del.

Допустим, в последовательности чисел от 0 до 9 нужно удалить 4, 5, 6 и 7. Тогда решение будет выглядеть так:

#Сначала создадим лист с числами от 0 до 9. num_list = list(i for i in range(10)) print(num_list) >>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] #После чего укажем срез чисел от 4 до 7. #Обратите внимание: элемент с индексом 8 не удаляется. del num_list[4:8] print(num_list) >>> [0, 1, 2, 3, 8, 9]

Как удалить последний элемент списка в Python

Если мы хотим избавиться от последнего элемента, то, как и в случае с первым, удобнее всего это сделать с помощью pop() или del.

С помощью метода pop()

Так как по умолчанию метод принимает аргумент -1, то можно вообще ничего не передавать:

num_list = ['ноль', 1, [2.1, 'два и два'], 3, 'IV'] num_list.pop() print (num_list) >>> ['ноль', 1, [2.1, 'два и два'], 3]

Но если вы истинный приверженец дзена Python («Явное лучше неявного»), то можно указать -1 — ничего не изменится.

С помощью ключевого слова del

А вот если хотите удалить последний элемент с помощью del, то передать -1 нужно обязательно:

num_list = ['ноль', 1, [2.1, 'два и два'], 3, 'IV'] del num_list[-1] print(num_list) >>> ['ноль', 1, [2.1, 'два и два'], 3]

Подведём итоги

Язык Python даёт четыре основных инструмента для удаления элементов из списка:

  • remove() — удаляет по названию;
  • pop() — удаляет по индексу, положительному или отрицательному;
  • clear() — удаляет всё содержимое списка;
  • del — позволяет удалить как отдельный элемент, так и целый срез по индексу.

Читайте также:

Источник

Оцените статью