Tuples#

  • A tuple, like a list, is a sequence of items of any type.

  • Unlike lists, however, tuples are immutable.

Type

Collection of

Syntax

Ordered

Indexed

Mutable

Passed By

Duplicates Allowed

strings

characters

" "

value

list

any data type

[ ]

reference

tuple

any data type

( )

value

  • Syntactically, a tuple is a comma-separated sequence of values:

tup1 = 2, 4, 6, 8, 10, 2
print(tup1)
(2, 4, 6, 8, 10, 2)
  • Although it is not necessary, it is conventional to enclose tuples in parentheses:

tup2 = (2, 4, 6, 8, 10, 2)
print(tup2)
(2, 4, 6, 8, 10, 2)
  • To create a tuple with a single element, we have to include the final comma:

listt = [5]
print(type(listt), listt)
<class 'list'> [5]
tup = (5,)
print(type(tup), tup)
<class 'tuple'> (5,)
  • Without the comma, Python treats (5) as an integer in parentheses:

tup = (5)
print(type(tup), tup)
<class 'int'> 5
  • Syntax issues aside, tuples support the same sequence operations as strings and lists.

  • The index operator selects an element from a tuple.

tup = ('a', 'b', 'c', 'd', 'e')
tup[4]
'e'
  • And the slice operator selects a range of elements.

tup = ('a', 'b', 'c', 'd', 'e')

tup[2:4]
('c', 'd')
  • Concatenation Operator + works the same as with lists and strings

tup1 = ('X',) 
tup2 = ('a', 'b', 'c', 'd', 'e')
tup = tup1 + tup2
tup
('X', 'a', 'b', 'c', 'd', 'e')
  • When we try to use item assignment to modify one of the elements of the tuple, we get an error:

tup = (1, 2, 3)
tup[0] = 'X'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [9], in <cell line: 2>()
      1 tup = (1, 2, 3)
----> 2 tup[0] = 'X'

TypeError: 'tuple' object does not support item assignment

Tuple assignment#

  • Once in a while, it is useful to swap the values of two variables.

    • With conventional assignment statements, we have to use a temporary variable.

  • For example, to swap a and b:

a = "a"
b = "b"
temp = a
a = b
b = temp
print(a, b)
b a
  • Python provides a form of tuple assignment that solves this problem neatly:

a = "a"
b = "b"
c = "c"
d = "d"

a, b, c, d = b, b, b, b

print(a, b, c, d)
b b b b
  • The left side is a tuple of variables; the right side is a tuple of values.

  • Each value is assigned to its respective variable.

  • This feature makes tuple assignment quite versatile.

  • The number of variables on the left and the number of values on the right have to be the same.

Tuples as return values#

  • Functions can return tuples as return values.

def find_min_max(numbers):
    

    min_val = 9999
    max_val = -9999

    i = 0
    while i < len(numbers):
        if numbers[i] < min_val:
            min_val = numbers[i]
        
        if numbers[i] > max_val:
            max_val = numbers[i]
            
        i = i + 1
        
    return min_val, max_val


minimum, maximum = find_min_max([3, 1, 5, 4, 2])
print(minimum, maximum)
1 5
  • Reminder: Tuples are passed to functions by value

  • Translation: Any changes you make inside a function, would NOT be reflected outside the function

def swap(inputs):
    x, y = inputs
    y, x = x, y
    
a, b = "a", "b"
swap((a, b))
print(a, b)

Exercises#

Question 1.#

Find below the exam score of three students Jane, John and Mary.

Compute the average exam score for the three.

student1 = ("Jane Doe", 80, "Chemistry")
student2 = ("John Doe", 75, "Computer Science")
student3 = ("Mary Sue", 100, "Maths")

avg = (student1[1] + student2[1] + student3[1])/3

print(avg)
85.0

Question 2.#

Write a function swap that accepts as input a tuple tup_in of length=2 and returns a tuple tup_out with values of tup_in swapped.

def swap(tup):
    
    

assert swap(("a", "b"))==("b", "a"), "Test case 1 failed"

Question 3.#

Write a function that accepts as input a list sequence and returns (first_item, last_item).

def get_first_and_last(sequence):
    return sequence[0], sequence[-1]
    
assert get_first_and_last([4, 5, 1, 3, 2])==(4, 2),    "Test case 1 passed"
assert get_first_and_last([42])           ==(42,42),   "Test case 2 passed"
assert get_first_and_last("apple")        ==("a","e"), "Test case 3 passed"

print("All test cases passed")