PYTHON

  minte9
REMEMBERS




Tuples

p208 A tuple is a comma separated values.
 
# A tuple is a comma separated values
# It is common to use parantheses, but not necessary
#
# A single value in parantheses is not a tuple
# For a single element, include the final comma
#
# Tuples are different than lists, they are immutable.
# Tuples are typed with parentheses, instead of square brackets.


# CLASS type
# -------------------------------------------
t = 'a', 'b', 'c'; 
t = 'a',
t = ('a', 'b', 'c')

print(type(t)) # <class 'tuple'>


# NOT a tuple
# -------------------------------------------
t = ('a')
print(type(t)) # <class 'str'>


# IMMUTABLE
# -------------------------------------------
mylist = [1, 2, 3]
mylist[0] = 4
print(mylist)  # [4, 2, 3]

mytuple = (1, 2, 3)
# mytuple[0] = 4 
#   # TypeError: 'tuple' object does not support item assignment


# REPLACE
# -------------------------------------------
# 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')

Variables

p211 It is often useful to swap the values of variables (tuple has an elegant syntax).
 
# Tuple elegant syntax to swap variables
c = 3
d = 4
c, d = d, c
assert (c, d)   == (4, 3)
assert (c)      == 4
assert (c,)     != 4
assert (c, d)   != (3, 4)

# Common method is to use a tmp variable
a = 1
b = 2
tmp = a
a = b
b = tmp
assert (a, b) == (2, 1)

# Example: Split an email address
name, domain = "office@google.com".split('@')
assert (name, domain) == ("office", "google.com")
assert domain == "google.com"

Dictionaries

p218 It is common to use tuples as keys in dictionaries (you can't use lists).
 
# You can't use lists with dictionaries
# Insteed, it is common to use tuples

dictonary = {
    ("Johny", "Cash"): 4007344455,
    ("John", "Lennon"): 400768696,
}

for a, b in dictonary:
    print(a, b, dictonary[a, b])
        # Johny Cash 4007344455
        # John Lennon 400768696

Functions

p212 A function can return only one value, but you can use turtle for multiple return values.
 
# A function can return only one value.
#
# If the value is a tuple ...
# the effect is the same as returning multiple values.


# Quontient & Reminder:
#
# To compute the quontient and reminders it is better to ...
# compute both at the same time.

quot = 7//3
rem = 7%3
assert (quot, rem) == (2, 1)

quot, rem = divmod(7, 3)  # built-in function
assert (quot, rem) == (2, 1)


# Function arguments:
#
# Functions can take a variable number of arguments.
# A parameter name that begins with * gathers arguments into a tuple.

t = (7, 3)
# divmod(t)  
#   TypeError: divmod expected 2 arguments, got 1

assert divmod(*t) == (2, 1)  # it works!

Questions     github Collections
References
        A B C D E F
🔔
1/3