Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Create tuple

  • tuple
  • ()

Tuple

  • A tuple is a fixed-length immutable list. It cannot change its size or content.
  • Can be accessed by index, using the slice notation.
  • A tuple is denoted with parentheses: (1,2,3)
planets = ('Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn')
print(planets)
print(planets[1])
print(planets[1:3])

planets.append("Death Star")
print(planets)

Output:

('Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn')
Venus
('Venus', 'Earth')
Traceback (most recent call last):
  File "/home/gabor/work/slides/python/examples/lists/tuple.py", line 6, in <module>
    tpl.append("Death Star")
AttributeError: 'tuple' object has no attribute 'append'

List

  • Elements of a list can be changed via their index or via the list slice notation.
  • A list can grow and shrink using append and pop methods or using the slice notation.
  • A list is denoted with square brackets: [1, 2, 3]
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn']
print(planets)
print(planets[1])
print(planets[1:3])

planets.append("Death Star")
print(planets)

Output:

['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn']
Venus
['Venus', 'Earth']
['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Death Star']

Tuples are rarely used. There are certain places where Python or some module require tuple (instead of list) or return a tuple (instead of a list) and in each place it will be explained. Otherwise you don't need to use tuples.

e.g. keys of dictionaries can be tuple (but not lists).