Create 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)


examples/lists/tuple.py

planets = ('Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn')
print(planets)
print(planets[1])
print(planets[1:3])

planets.append("Death Star")
print(planets)
('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]


examples/lists/list.py

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn']
print(planets)
print(planets[1])
print(planets[1:3])

planets.append("Death Star")
print(planets)
['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn']
Venus
['Venus', 'Earth']
['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Death Star']