Python-Ref > Data structures > Sequence types in general > Looping over a sequence
 
 

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

Looping over a sequence

How to do something for each member of a sequence.
In this example we will only briefly mention some of the methods of looping over a sequence. More on these methods is discussed elsewhere, see for instance - Looping.
The for loop is usually the most interesting one for looping over a sequence.
Expand/Shrink
Zdroj: (sequence3-1.py)
  1   xs = [10,20,40,23]
  2   string = "Don't panic"
  3   
  4   for x in xs:
  5       print x, x*x
  6   
  7   for ch in string:
  8       print ch
stdout:
10 100
20 400
40 1600
23 529
D
o
n
'
t
 
p
a
n
i
c
Doba běhu: 21.3 ms
The same effect as in the previous example can be achived by looping over the indexes instead of sequence items.
Expand/Shrink
Zdroj: (sequence3-4.py)
  1   string = "Don't panic"
  2   
  3   for i in range( len( string)):
  4       ch = string[i]
  5       print i, ch
stdout:
0 D
1 o
2 n
3 '
4 t
5  
6 p
7 a
8 n
9 i
10 c
Doba běhu: 21.5 ms
Sometimes it is useful to loop over a sequence and also have the information about the index of the item we currently handle. This may be accomplished either by simply defining a counter variable and increment it after every cycle..
Expand/Shrink
Zdroj: (sequence3-3.py)
  1   string = "Don't panic"
  2   
  3   # one version
  4   i = 0
  5   for ch in string:
  6       print ch, i,            # we prevent a newline using the trailing comma
  7       i += 1
  8   
  9   print   # to finish the line
stdout:
D 0 o 1 n 2 ' 3 t 4   5 p 6 a 7 n 8 i 9 c 10
Doba běhu: 20.8 ms
..or by using the built-in function enumerate that is available in Python from version 2.3.
Expand/Shrink
Zdroj: (sequence3-2.py)
  1   string = "Don't panic"
  2   
  3   # one version
  4   for tup in enumerate( string):   # tup will be a tuple of (index, item)
  5       i, ch = tup                  # tuple unpacking
  6       print ch, i,                 # we prevent a newline using the trailing comma
  7   
  8   print   # to finish the line
  9   
 10   
 11   # there is a more elegant way still
 12   for i,ch in enumerate( string):   # the unpacking is done here
 13       print ch, i,
stdout:
D 0 o 1 n 2 ' 3 t 4   5 p 6 a 7 n 8 i 9 c 10
D 0 o 1 n 2 ' 3 t 4   5 p 6 a 7 n 8 i 9 c 10
Doba běhu: 21.7 ms