3  Tuples

Tuples are immutable

x = (23, 7, 9, 7)
x
(23, 7, 9, 7)
type(x)
tuple

There are two builtin methods for tuples:

x.count(7)
2
x.index(9)
2

3.1 enumerate()

enumerate() outputs pairs of index and value of an iterable object:

for i,val in enumerate(x):
    print("i is", i, "and val is", val)
i is 0 and val is 23
i is 1 and val is 7
i is 2 and val is 9
i is 3 and val is 7

A list comprehension using enumerate() with an if condition is a quick way to find all occurences of a value in a collection:

[i for i,v in enumerate(x) if v==7]
[1, 3]

3.2 Named tuples

Python docs: namedtuple()

namedtuple() creates a new tuple subclass with named fields

from collections import namedtuple
Person = namedtuple('Person',
                    ['First_Name', 'Last_Name', 'City'])
x = Person('John', 'Summers', 'Philadelphia')

Access field directly (REPL):

x.First_Name
'John'

Access field programmatically using field name in a variable:

key = 'City'
getattr(x, key)
'Philadelphia'

3.3 zip() iterables to output tuples

day = ['Sunday', 'Monday', 'Tuesday',  'Wednesday']
temperature = [16, 18, 19, 24]
list(zip(day, temperature))
[('Sunday', 16), ('Monday', 18), ('Tuesday', 19), ('Wednesday', 24)]