1. Tuple

tup = 4, 5, 6
tup
## (4, 5, 6)
tup2 = (1, 2)
tup2
## (1, 2)
tup3 = (1, "2", True)
tup3
## (1, '2', True)
nested_tup = (4, 5, 6), (7, 8)
nested_tup
## ((4, 5, 6), (7, 8))
tuple([4, 0, 2])
## (4, 0, 2)
tuple("string")
## ('s', 't', 'r', 'i', 'n', 'g')

2. Elements of a Tuple

tup = ('hello', 2, 'you')
tup[0]
## 'hello'
e1 = 'foo'
e2 = [1, 2]
tup = (e1, e2)
tup
## ('foo', [1, 2])
e2[0] = 3
e2
## [3, 2]
tup
## ('foo', [3, 2])
tup[1][1] = 4
tup
## ('foo', [3, 4])

3. Tuple Concatenation

(4, None, 'foo') + (6, 0) + ('bar',)
## (4, None, 'foo', 6, 0, 'bar')
tup = ('foo', [1, 2])*4
tup
## ('foo', [1, 2], 'foo', [1, 2], 'foo', [1, 2], 'foo', [1, 2])

tup[1][0] = 5
tup
## ('foo', [5, 2], 'foo', [5, 2], 'foo', [5, 2], 'foo', [5, 2])

4. Unpacking Tuples

tup = (4, 5, 6)
a, b, c = tup
a
## 4
b
## 5
c
## 6
tup = 4, 5, (6, 7)
a, b, (c, d) = tup
d
## 7
seq = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
for a, b, c in seq:
  print('a={0}, b={1}, c={2}'.format(a, b, c))
## a=1, b=2, c=3
## a=4, b=5, c=6
## a=7, b=8, c=9
values = 1, 2, 3, 4, 5
a, b, *rest = values
a
## 1
b
## 2
rest
## [3, 4, 5]

5. count()

a = (1, 2, 2, 2, 3, 4, 5)
a.count(2)
## 3

Exercise

Some students’ information is stored in a nested tuple where each inner tuple represents a student.

students = (('Ha', 25, True), ('Alex', 50, False), ('Dave', 34, False), ('Lelys', 50, True))

For each inner tuple, the information is stored in the following format (name, age, is female?).

Unpack this tuple and store all students name in a string (separated by comma ,), and all students’ ages together and count the number of female and male students (store them in female_count and male_count).

This lecture note is modified from Chapter 3 of Wes McKinney’s Python for Data Analysis 2nd Ed.