CIS 111 Tuples

Objectives

  • Describe what a tuple is
  • Create tuples in Python
  • Use Python tuples
  • Access elements of a tuple
  • Access tuple documentation
  • Use a generator to create a tuple

Tuple overview

  • tuples are an instance of the tuple class
  • to get tuple documentation: help(tuple)
  • tuples are like lists, but...
    • they are immutable
    • they do not have as many features
    • they are surrounded by an optional set of parentheses
  • a tuple can be a single item in another tuple
  • a tuple is an immutable ordered sequence of values
  • empty tuple: ()
  • tuple with one item: ('a', ) # need the trailing comma

Tuple examples

help(tuple) # displays tuple documentation mytuple = () # creates empty tuple print(len(mytuple)) # 0 tpl1 = (1, 2, 3) # creates three element tuple mytuple = tpl1, 4, 5 # creates three element tuple print(mytuple) # (1, 2, 3), 4, 5 print(len(mytuple)) # 3 print(mytuple.count(5)) # 1 (occurrences of 5) print(mytuple.count(2)) # 0 (occurrences of 2) print(mytuple.count((1,2,3)) # 1 (occurrences of (1, 2, 3)) print(mytuple.index((1,2,3))) # 0 (where item is in tuple) print(mytuple.index(4)) # 1 (where item is in tuple) print(mytuple.index(6)) # ValueError (item is not in tuple) print(mytuple[1]) # 4 print(mytuple[0]) # (1, 2, 3) print(mytuple[0][1]) # 2 (second item in first element of tuple) # example of using a generator when creating a tuple x = tuple(i for i in range(1, 30, 4)) print(x) # (1, 5, 9, 13, 17, 21, 25, 29)