8. tuple

  • Can store elements of any types
  • Immutable - cannot add, modify or remove items
  • Brackets are optional
  • Comma after last element is optional
  • Single element tuple require comma at the end (important!)

8.1. Defining tuple

  • tuple() is more readable
  • () is used more often

8.1.1. Empty tuple

my_tuple = ()
my_tuple = tuple()

8.1.2. tuple with one element

my_tuple = 1,
my_tuple = (1,)

8.1.3. tuple with many elements

my_tuple = 1, 2
my_tuple = (1, 2)
my_tuple = 1, 2.0, None, False, 'José'
my_tuple = (1, 2.0, None, False, 'José')

8.2. Slicing tuple

my_tuple = (1, 2, 3, 4, 5)

my_tuple[2]             # 3
my_tuple[-1]            # 5
my_tuple[:3]            # (1, 2, 3)
my_tuple[3:]            # (4, 5)
my_tuple[::2]           # (1, 3, 5)
my_tuple[1:4]           # (2, 3, 4)

8.3. Length of a tuple

my_tuple = (1, 2, 3)

len(my_tuple)           # 3