Python-Ref > Data structures > Sequence types in general > Searching for an item in a sequence
 
 

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

Searching for an item in a sequence

How to find out if a sequence contains specified item and where.
To check presence of an item in a sequence, one uses the keyword in.
Expand/Shrink
Zdroj: (sequence4-1.py)
  1   string = "Hi there."
  2   xs = [1,2,4,10,3,8,1,2]
  3   
  4   print "i" in string
  5   print "x" in string
  6   
  7   print 1 in xs
  8   print 50 in xs
  9   print "1" in xs
stdout:
True
False
True
False
False
Doba běhu: 20.9 ms
To get the position (index) of an item in a sequence, the method index is used.
Expand/Shrink
Zdroj: (sequence4-2.py)
  1   string = "Hi there."
  2   xs = [1,2,4,10,3,8,1,2]
  3   
  4   print string.index( "i")
  5   
  6   print xs.index( 1)      # the first occurence is reported here
  7   print xs.index( 1, 3)   # optional second argument to 'index' is the smallest
  8                           # after which to look for an item 
  9   
stdout:
1
0
6
Doba běhu: 21.3 ms
It is wise to check if an item is present in a sequence, before trying to get its index.
Expand/Shrink
Zdroj: (sequence4-3.py)
  1   string = "Hi there."
  2   
  3   print string.index( "z")   # index on non-existing item will fail
stderr:
Traceback (most recent call last):
  File "sequence4-3.py", line 3, in ?
    print string.index( "z")   # index on non-existing item will fail
ValueError: substring not found
Doba běhu: 21.0 ms
This is how you fix it.
Expand/Shrink
Zdroj: (sequence4-5.py)
  1   string = "Hi there."
  2   
  3   if "z" in string:
  4     print string.index( "z")
  5   else:
  6     print "'z' was not found"
stdout:
'z' was not found
Doba běhu: 19.8 ms
This method is not available for all sequence type. List and string provide it, but for example tuple does not.
Expand/Shrink
Zdroj: (sequence4-4.py)
  1   t = (1,2,3,"hi")
  2   
  3   print t.index( 2)   # index is not available for tuples
stderr:
Traceback (most recent call last):
  File "sequence4-4.py", line 3, in ?
    print t.index( 2)   # index is not available for tuples
AttributeError: 'tuple' object has no attribute 'index'
Doba běhu: 21.8 ms