REMEMBER PYTHON

MINTE9 2REMEMBER

Last update:   23-07-2021

Tuples

p208 A tuple is a sequence of values (can be any type), indexed by integers. Tuples are immutable, they are not like lists.
 RunCode
# 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'>
... 12 lines˄˄˄
 RunCode
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
... 7 lines˄˄˄
p210 ! Because tuples are immutable, you can't modify the elements. But you can replace one tuple with another.
 RunCode
t = ('a', 'b', 'c', 'd', 'e')
t = ('A',) + t[2:]
print(t)  # ('A', 'c', 'd', 'e')
... 3 lines˄˄˄
p211 It is often useful to swap the values of variables. Tuple has a more elegant syntax.
 RunCode
# 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

... 16 lines˄˄˄
p218 It is common to use tuples as keys in dictionaries (you can't use lists).
 CodeCopy

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
... 9 lines˄˄˄

Questions
CARD
19
32

A B C D E F
🔔
1/1