minte9
LearnRemember



Tuples

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.


# tuple type
# -------------------------------------------
t1 = 'a', 'b', 'c'
t2 = ('a', 'b', 'c')
print(type(t1)) # <class 'tuple'>
print(type(t2)) # <class 'tuple'>

# NOT a tuple
# -------------------------------------------
t3 = 'a'
t4 = ('a')
print(type(t3)) # <class 'str'>
print(type(t4)) # <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

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

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

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!



  Last update: 432 days ago