Python-Ref > Data structures > Tuple > Typical tuple usage
 
 

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

Typical tuple usage

This example focuses on usage of tuples that is typical. As a sequence type, tuple shares some properties with lists and strings. These properties are described in chapter Sequence types in general.
Tuples are conveniently used for assignment of values to several variables. This feature is called tuple unpacking.
Expand/Shrink
Zdroj: (tuple2.py)
  1   tuple1 = (1,2,3,"word",3.33)    # this is a tuple
  2   
  3   a,b,c,d,e = tuple1  # we have a tuple on both left and right side
  4                       # this lead so assignment of corresponding values
  5                       # the variables on the left side
  6   
  7   print a
  8   print b+c
  9   print d,e
stdout:
1
5
word 3.33
Doba běhu: 21.2 ms
Tuple unpacking can be used for value-swapping that would otherwise need a third variable to hold one of the values.
Expand/Shrink
Zdroj: (tuple3.py)
  1   a = 3
  2   b = 10
  3   print a, b
  4   
  5   # now we would like to set a=b and b=a, swapping their values
  6   
  7   # the non-python way is
  8   c = a
  9   a = b
 10   b = c
 11   print a, b
 12   
 13   # the python way uses tuple unpacking
 14   a, b = b, a  # we pack the values into a tuple on right side and upack on left side
 15   print a, b
stdout:
3 10
10 3
3 10
Doba běhu: 20.9 ms
When using tuple unpacking it is important to watch the length of the tuples. It must be the same on both sided.
Expand/Shrink
Zdroj: (tuple4.py)
  1   a,b = 1,2   # no problem here
  2   print a
  3   print b
  4   
  5   
  6   c,d = 10,20,30   # this is an error
stdout:
1
2
stderr:
Traceback (most recent call last):
  File "tuple4.py", line 7, in ?
    c,d = 10,20,30   # this is an error
ValueError: too many values to unpack
Doba běhu: 21.4 ms
The most interesting use of tuples is described in example Returning more values from a function.