How to remove the first element from a list in python?

Asked

Viewed 10,914 times

5

I have the following code:

On the command line

> teste.py primeiro segundo

In the script teste.py:

import sys

print(sys.argv)

And I have the following return:

['c:\\teste.py', 'primeiro', 'segundo']

But I’d like to remove the first element. What are the possible ways to remove the first of a list in the Python?

3 answers

5


The method can also be used del to remove an item by specifying its index.

lista = ['foo', 'bar', 'baz']
del lista[0]

print lista # ['bar', 'baz']

The difference between pop and del is that pop returns the value removed, while del only remove.

Take an example:

lista1 = ['foo', 'bar', 'baz']
lista2 = ['aaa', 'bbb', 'ccc', 'ddd']

del lista1[0]
deleted = lista2.pop(0)

print (lista1) # ['bar', 'baz']
print (lista2) # ['bbb', 'ccc', 'ddd'] 
print ("O valor %s foi deletado da lista1" % deleted) # O valor aaa foi deletado da lista1

DEMO

There is also the method remove() that, instead of specifying the index, the value is used to remove it from the list.

lista = ['foo', 'bar', 'baz']
lista.remove('foo')

print lista # ['bar', 'baz']

The method remove will remove the first corresponding value, assuming that the list has two equal values, only the first will be removed.

4

Use the method pop, documentation here:

lista = sys.argv
lista.pop(0)
  • In the case, lista has the first element removed and lista.pop(0) returns the element that has been removed?

  • This, if you only use lista.pop() remove and return the last item from the list. @Wallacemaxters

3

Another way would be to pick up items from the second item in the list:

>>> a = [a, b, c, d, e, f]
>>> a = a[1:]
[b, c, d, e, f]
  • 1

    cool! I did the test here. The only difference is that it doesn’t literally remove, but it just returns without the first element

Browser other questions tagged

You are not signed in. Login or sign up in order to post.