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

5

I have the following code:

At 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 would like to remove the first element. What are the possible ways to remove the first from a list in Python ?

    
asked by anonymous 05.02.2015 / 15:21

3 answers

4

You can also use the del method to remove a item specifying your index.

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

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

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

See 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 remove() method that, instead of specifying the index, is used to remove it from the list.

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

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

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

    
05.02.2015 / 16:07
3

Use the pop method, documentation here :

lista = sys.argv
lista.pop(0)
    
05.02.2015 / 15:33
2

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

>>> a = [a, b, c, d, e, f]
>>> a = a[1:]
[b, c, d, e, f]
    
10.02.2015 / 05:33