Python-Ref > Data structures > Sequence types in general > Item retrieval
 
 

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

Item retrieval

To retrieve and item from a sequence (a letter in case of strings) you use the bracket notation described in the example below.
Expand/Shrink
Zdroj: (sequence1-1.py)
  1   a_list = [1,2,3,4,6]                  # list of 5 intergers
  2   a_tuple = ("this","is","a","tuple")   # tuple of 4 strings
  3   a_string = "An example string"        # a string
  4   
  5   
  6   print a_list[0]   # indexing starts from 0
  7   print a_list[2]
  8   
  9   print a_tuple[1]
 10   print a_tuple[0][1]   # the second character of the first string in a_tuple
 11   
 12   print a_string[8]
stdout:
1
3
is
h
l
Doba běhu: 21.2 ms
The interger that is given in brackets is called index and starts from 0. It is possible to use negative integers to retrieve items from the end of the sequence. This is usefull when we know that we need to retrieve the last item but the length of the sequence varies. In this case the indexing starts from -1 as -0 is 0.
Of course, the index might as well be stored in a variable.
Expand/Shrink
Zdroj: (sequence1-2.py)
  1   a_list = [1,2,3,4,6]                  # list of 5 intergers
  2   a_tuple = ("this","is","a","tuple")   # tuple of 4 strings
  3   a_string = "An example string"        # a string
  4   
  5   
  6   print a_list[-1]   # the last item
  7   
  8   i = -1
  9   print a_tuple[i][0]   # first character of the i-th (last) item
 10   
 11   print a_string[-2]   # the character before last
stdout:
6
t
n
Doba běhu: 21.3 ms
One has to be careful to use only indexes that are in the range of sequences length, otherwise an error occurs. This is especially important to keep in mind for beginners that are not used to the fact that the indexing starts from 0 and therefor the index of the last item is the length of the sequence minus 1.
Expand/Shrink
Zdroj: (sequence1-3.py)
  1   a_list = [1,2,3,4,6]                  # list of 5 intergers
  2   
  3   print a_list[5]   # the last item
stderr:
Traceback (most recent call last):
  File "sequence1-3.py", line 4, in ?
    print a_list[5]   # the last item
IndexError: list index out of range
Doba běhu: 21.1 ms
Also take care of empty sequences - they do not have even the first (x[0]) item.
Expand/Shrink
Zdroj: (sequence1-4.py)
  1   empty_string = ""
  2   
  3   print empty_string[0]   # this is an error
stderr:
Traceback (most recent call last):
  File "sequence1-4.py", line 4, in ?
    print empty_string[0]   # this is an error
IndexError: string index out of range
Doba běhu: 21.2 ms