Tuples

Creating Tuples

  1. # create tuple
  2. point = (3, 5)
  3. rgb = (255, 128, 0)
  4. single = (42,)
  5. #ans: note comma for single element
  6. empty = ()

Accessing Elements

  1. # indexing tuples
  2. point = (3, 5)
  3. point[0]
  4. #ans: 3
  5. point[-1]
  6. #ans: 5

Tuple Unpacking

  1. # unpack values
  2. x, y = (3, 5)
  3. #ans: x=3, y=5
  4. r, g, b = (255, 128, 0)
  5. #ans: r=255, g=128, b=0

Tuples are Immutable

  1. # cannot modify
  2. point = (3, 5)
  3. #ans: point[0] = 10 # TypeError

Tuple Operations

  1. # concatenation
  2. tuple1 = (1, 2)
  3. tuple2 = (3, 4)
  4. tuple1 + tuple2
  5. #ans: (1, 2, 3, 4)
  6. #ans: repetition
  7. (1, 2) * 3
  8. #ans: (1, 2, 1, 2, 1, 2)

Tuple Methods

  1. # count
  2. numbers = (1, 2, 3, 2, 4)
  3. numbers.count(2)
  4. #ans: 2
  5. #ans: index
  6. numbers.index(3)
  7. #ans: 2

Exercises - Part 1

  1. # single element tuple?
  2. x = (5)
  3. type(x)
  4. #ans: <class 'int'>
  5. y = (5,)
  6. type(y)
  7. #ans: <class 'tuple'>

Exercises - Part 2

  1. # tuple unpacking?
  2. a, b = (10, 20)
  3. #ans: a=10, b=20

Exercises - Part 3

  1. # can you modify?
  2. t = (1, 2, 3)
  3. t[0] = 10
  4. #ans: TypeError (tuples are immutable)

Exercises - Part 4

  1. # tuple slicing?
  2. t = (1, 2, 3, 4, 5)
  3. t[1:4]
  4. #ans: (2, 3, 4)

Exercises - Part 5

  1. # nested tuple?
  2. t = ((1, 2), (3, 4))
  3. t[0][1]
  4. #ans: 2

Exercises - Part 6

  1. # tuple with list?
  2. t = (1, [2, 3], 4)
  3. t[1].append(5)
  4. #ans: t is (1, [2, 3, 5], 4)

Exercises - Part 7

  1. # empty tuple length?
  2. t = ()
  3. len(t)
  4. #ans: 0

Exercises - Part 8

  1. # tuple from string?
  2. t = tuple("abc")
  3. #ans: ('a', 'b', 'c')

Exercises - Part 9

  1. # comparing tuples?
  2. (1, 2) == (1, 2)
  3. #ans: True
  4. (1, 2) < (1, 3)
  5. #ans: True

Exercises - Part 10

  1. # tuple membership?
  2. 3 in (1, 2, 3)
  3. #ans: True

Google tag (gtag.js)