There are several ways to delete elements from a list.
If you know a specific element and index
of element you want to delete you can use pop method:
>>> t = ['a', 'b', 'c'] >>> x = t.pop(1) >>> print t ['a', 'c'] >>> print x b
Pop method modifies the list and returns the element
that was removed. If you don’t provide an index, it deletes and returns the
last element.
>>> t = ['a', 'b', 'c'] >>> x = t.pop() >>> print t ['a', 'b'] >>> print x c
If
you don’t need removed value but just want to delete removed value, you can use
the del operator:
>>> t = ['a', 'b', 'c'] >>> del t[1] >>> print t ['a', 'c']
If you know the element you want to remove (but not
the index), you can use remove:
>>> t = ['a', 'b', 'c'] >>> t.remove('b') >>> print t ['a', 'c']
The remove method return value is None. To remove more
than one element, you can use del with a slice index:
>>> t = ['a', 'b', 'c', 'd', 'f'] >>> del t[1:] >>> print t ['a']
Slice selects all the elements up to, but not
including, the second index.
Nema komentara:
Objavi komentar