Python-Ref > Data structures > List > Removing items from a list
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Removing items from a list

To remove an item based on its index, use the keyword del.
Expand/Shrink
Zdroj: (list4-1.py)
  1   list1 = range( 10)
  2   list2 = ["one","two","three"]
  3   
  4   print list1
  5   del list1[1]
  6   print list1
  7   del list1[3:8]
  8   print list1
  9   print
 10   
 11   print list2
 12   del list2[ list2.index("one")]
 13   print list2
stdout:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 3, 9]

['one', 'two', 'three']
['two', 'three']
Doba běhu: 36.5 ms
The same effect is accomplished using the method pop with difference that the deleted item is returned by the method.
Expand/Shrink
Zdroj: (list4-2.py)
  1   sts = ["one","two","three"]
  2   
  3   while sts:
  4       st = sts.pop(0)
  5       print st, sts
stdout:
one ['two', 'three']
two ['three']
three []
Doba běhu: 21.3 ms
This method can be used to destructively process the content of a list.
To remove an item based on its content and not its index, the method remove is used.
Expand/Shrink
Zdroj: (list4-3.py)
  1   sts = ["one","two","three"]
  2   
  3   print sts
  4   sts.remove( "two")
  5   print sts
stdout:
['one', 'two', 'three']
['one', 'three']
Doba běhu: 21.3 ms
Take care not to try to remove something that is not there.
Expand/Shrink
Zdroj: (list4-4.py)
  1   sts = ["one","two","three"]
  2   
  3   print sts
  4   sts.remove( "four")
  5   print sts
stdout:
['one', 'two', 'three']
stderr:
Traceback (most recent call last):
  File "list4-4.py", line 4, in ?
    sts.remove( "four")
ValueError: list.remove(x): x not in list
Doba běhu: 21.1 ms