Python-Ref > Data structures > Tuple > What is a tuple
 
 

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

What is a tuple

Tuple in one of the sequence types, together with strings or lists and therefor shares some of their properties.
Tuples are not mutable, so once a tuple is created it cannot be changed. Tuples also lack some other properties of lists, but this is really not a problem. Tuples are usually used to pack several values together, for example when it is necessary to return more than one value from a function. They may also be sometimes used as a lightweight replacement for lists.
Tuples are constructed by putting several values together separated with commas. It is usefull and sometimes necessary to enclose the tuple inside brackets.
Expand/Shrink
Zdroj: (tuple1.py)
  1   tuple1 = (1,2,3,"word",3.33)    # this is a tuple
  2   tuple2 = 4,5,"another","words"  # this is also a tuple
  3   tuple3 = (3,)                   # tuple with one item must have a trailing comma
  4   tuple4 = 3,                     # one-item tuple without the brackets
  5   tuple5 = ()                     # empty tuple
  6   
  7   non_tuple = (3)   # this is not a tuple but simply the value 3 in brackets
  8   
  9   
 10   print tuple1
 11   print tuple2
 12   print tuple3
 13   print tuple4
 14   print tuple5
 15   
 16   print non_tuple
stdout:
(1, 2, 3, 'word', 3.3300000000000001)
(4, 5, 'another', 'words')
(3,)
(3,)
()
3
Doba běhu: 21.3 ms
Tuple may be also part of other tuples. Thus more complicated structures might be constructed.
Expand/Shrink
Zdroj: (tuple1-1.py)
  1   tuple1 = (1,2,3)
  2   tuple2 = ("A","b","c")
  3   tuple3 = tuple2, tuple1
  4   
  5   print tuple3
  6   
  7   tuple4 = tuple3, "some more"
  8   print tuple4
stdout:
(('A', 'b', 'c'), (1, 2, 3))
((('A', 'b', 'c'), (1, 2, 3)), 'some more')
Doba běhu: 21.1 ms