PROGRAMMING

m9/ PYTHON
REMEMBERS




Tuples

p208 A tuple is a sequence of values (can be any type), indexed by integers. Tuples are immutable, they are not like lists.
 
# a tuple is a comma separated values
t = 'a', 'b', 'c'
print(type(t))  # <class 'tuple'>

# include the final comma, for a single element
t = 'a',
print(type(t))  # <class 'tuple'>

# not necessary, but it is common to use parantheses
t = ('a', 'b', 'c')
print(type(t))  # <class 'tuple'>

# a value in parantheses is not a tuple
t = ('a')
print(type(t)) # <class 'str'>
... 6 lines
 
 
mylist = [1, 2, 3]
mylist[0] = 4
print(mylist)  # [4, 2, 3]

mytuple = (1, 2, 3)
mytuple[0] = 4
print(mytuple)  
    # TypeError: 'tuple' object does not support item assignment
... 1 lines
 
p210 ! Because tuples are immutable, you can't modify the elements. But you can replace one tuple with another.
 
t = ('a', 'b', 'c', 'd', 'e')
t = ('A',) + t[2:]
print(t)  # ('A', 'c', 'd', 'e')
p211 It is often useful to swap the values of variables. Tuple has a more elegant syntax.
 
# swap variables
a = 1
b = 2

tmp = a
a = b
b = tmp
print(a, b)  # 2 1

# tuple more elegant syntax
c = 3
d = 4
c, d = d, c
print(c, d)  # 4 3

# split an email address
addr = 'office@google.com'
name, domain = addr.split('@')
print(name, domain)  # office google.com
... 10 lines
 
p218 It is common to use tuples as keys in dictionaries (you can't use lists).
 

last = "Moore"
first = "John"
number = "4007344455"

directory = {}
directory[last, first] = number
    # the expresion in the brakets is a tuple

for last, first in directory:
    print(first, last, directory[last, first])
        # John Moore 4007344455
... 3 lines
 

Questions    
Functions

        A B C D E F
🔔
1/1