= (23, 7, 9, 7)
x x
(23, 7, 9, 7)
Tuples are immutable
= (23, 7, 9, 7)
x x
(23, 7, 9, 7)
type(x)
tuple
There are two builtin methods for tuples:
.count(x)
: Count occurences of “x” in the tuple.index(x)
: Find position of “x” in the tuple7) x.count(
2
9) x.index(
2
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:
for i,v in enumerate(x) if v==7] [i
[1, 3]
namedtuple()
creates a new tuple subclass with named fields
from collections import namedtuple
= namedtuple('Person',
Person 'First_Name', 'Last_Name', 'City']) [
= Person('John', 'Summers', 'Philadelphia') x
Access field directly (REPL):
x.First_Name
'John'
Access field programmatically using field name in a variable:
= 'City'
key getattr(x, key)
'Philadelphia'
zip()
iterables to output tuples= ['Sunday', 'Monday', 'Tuesday', 'Wednesday']
day = [16, 18, 19, 24]
temperature list(zip(day, temperature))
[('Sunday', 16), ('Monday', 18), ('Tuesday', 19), ('Wednesday', 24)]