Python Programming

Lecture 5 Tuples, Function Basics

5.1 Tuples

  • A tuple is a sequence of values much like a list. The important difference is that tuples are immutable

  • The empty tuple can be written as tuple().

  • 
    >>> t = () #Empty is False
    >>> print(t)
    () 
    
    >>> t = ('a', 'b', 'c', 'd', 'e')
    
  • To create a tuple with a single element, you have to include the final comma:


>>> t1 = ('a',)
>>> type(t1)
tuple

>>> t2 = ('a')
>>> type(t2)
str
  • Most list operators also work on tuples. The bracket operator indexes an element:


>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print(t[0])
'a'

>>> print(t[1:3])
('b', 'c')

>>> print('a' in t) # in operator
True
  • Tuple is immutable. You can't modify the elements of a tuple, but you can replace one tuple with another:


>>> t[0] = 'A'
TypeError: object doesn't support item assignment
>>> t = ('A',) + t[1:]
>>> print(t)
('A', 'b', 'c', 'd', 'e')
  • If you want to modify a tuple, you can convert it to a list, and then convert it back.


>>> t = (1,2,3)
>>> s = list(t) # s = [1,2,3]
>>> s.pop()
>>> t = tuple(s) # t = (1,2)
  • Tuple assignment (multiple assignments)


>>> m = [ 'have', 'fun' ]
>>> (x, y) = m
>>> x
'have'
>>> y
'fun'
>>>

>>> m = [ 'have', 'fun' ]
>>> x, y = m
>>> x
'have'
>>> y
'fun'
>>> x, y = y, x #swap
  • Comparing Tuples


>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
  • Sorting Tuples


>>> t=[(2, 4), (0, 1, 2), (0, 3, 4)]
>>> t.sort()
>>> print(t)
  • Example: Tuple assignment and Comparison


txt = 'but soft what light in window'
words = txt.split()
t = list()
for word in words:
    t.append((len(word), word))
print(t)

[(3, 'but'), (4, 'soft'), (4, 'what'), (5, 'light'), (2, 'in'), (6, 'window')]

t.sort(reverse=True)
res_1 = list()
for length, word in t: 
    res_1.append(word)
print(res_1)

['window', 'light', 'what', 'soft', 'but', 'in']

t.sort(reverse=True)
res_2 = list()
for x in t:
    res_2.append(x)
print(res_2)
  • Lists and Tuples

  • Lists can be in a tuple, and tuples can be in a list.


>>> s = [('a', 'b'), ('A', 'B')]
>>> t = ('a', 'b', ['A', 'B'])
>>> t[2][0] = 'X'
>>> t[2][1] = 'Y'
>>> t
('a', 'b', ['X', 'Y'])

>>> t = ('a', 'b', ['A', 'B'])
>>> t[2] = ['X', 'Y']

TypeError: 'tuple' object does not support item assignment

>>> t = ('a', 'b', ('A', 'B'))
>>> t[2][0] = 'X'

TypeError: 'tuple' object does not support item assignment
  • Dictionaries and tuples


>>> d = {'a':10, 'b':1, 'c':22}
>>> t = list(d.items())
>>> t
[('b', 1), ('a', 10), ('c', 22)]
  • Using tuples as keys in dictionaries


>>> directory = dict()
>>> directory[('Taylor', 'Swift')] = 100
>>> print(directory)

{('Taylor', 'Swift'): 100}

Tuples: Summary

  • The element can be any type. The empty is ().

  • Features: Ordered, Immutable, Repeatable

  • Index and slice are the same with that of lists.

  • You cannot modify the elements of a tuple, but you can replace one tuple with another.

  • Multiple assignment with tuples.

  • Tuples can be keys of a dictionary.

5.2 List, dictionary, tuple

Comparison

Empty Feature
List [], list() ordered; mutable; repeatable
Tuple (), tuple() ordered; immutable; repeatable
Dictionary {}, dict() not ordered; key-value pairs and values are mutable, keys are not; values are repeatable, keys are not

Mutable and Immutable (可变和不可变)

  • Values are immutable. Thus, numbers, strings, tuples are immutable. Lists, dictionaries are mutable.

  • What does it mean for immutable or mutable? Assignment, Modification, Reference

  • 1. what is assignment? variable $\rightarrow$ computer memory $\rightarrow$ object

2. Modification

  • When you want to modify the immutable object, you can only assign a new object. It changes the address in the memory.
  • 
    >>> x = "abc"
    >>> x = "def"
    
  • There are two ways for you to modify the mutable object. a. make a new assignment; b. make a modification by methods for lists or some ways for dictionaries.
  • a. make a new assignment

    
    >>> x = [1,2,3]
    >>> x = [4,5,6]
    

b. make a modification by methods for lists. You do not change the address.


>>> x = [1,2,3]
>>> del x[2]
>>> del x[1]
>>> del x[0]
>>> x.append(4)
>>> x.append(5)
>>> x.append(6)

3. Reference


>>> x = "abc"
>>> y = x
>>> x = "def"
>>> print(y)
"abc"

>>> x = [1,2,3]
>>> y = x
>>> del x[2]
>>> x.append(4)
>>> print(y)
[1,2,4]

>>> x = [1,2,3]
>>> y = x[:] 
>>> del x[2]
>>> x.append(4)
>>> print(y)
[1,2,3]

a=a+b and a+=b


>>> x = 1
>>> y = x
>>> x = x + 1
>>> print(x,y)
2 1
>>> x+=1
>>> print(x,y)
3 1

>>> x = [1,2,3]
>>> y = x
>>> x += [4,5]
>>> print(x,y)
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
>>> x = x + [6,7]
>>> print(x,y)
[1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 4, 5]

5.3 Functions (1)

  • A function is a named sequence of statements that performs a computation.

  • Build-in Functions

    int(), float(), str(), type() and etc.

  • To make your own functions, two steps: 1. define a function 2. call a function

  • 
    def lyrics():
        print("I'm okay.")
    
    lyrics()
    
  • The first line of the function is called the header. The rest is called the body. You can use it inside another function

  • 
    def repeat_lyrics():
        lyrics()
        lyrics()
    
    repeat_lyrics()
    
    
    I'm okay.
    I'm okay.
    

Parameters and arguments


def print_twice(bruce): 
    print(bruce)
    print(bruce)

print_twice('Spam')
print_twice(17)

Spam
Spam
17
17

michael = 'Eric, the half a bee.'
print_twice(michael)

Eric, the half a bee.
Eric, the half a bee.

Multiple parameters

  • Positional Arguments


def describe_pet(type, name):
    print("My {}'s name is {}.".format(type,name))

describe_pet('hamster', 'Harry')
describe_pet('dog', 'Willie')

My hamster's name is Harry.
My dog's name is Willie.

describe_pet('harry', 'Hamster') #Order Matters

My harry's name is Hamster.
  • Keyword Arguments


def describe_pet(type, name):
    print("My {}'s name is {}.".format(type,name))

describe_pet(type='hamster', name='harry')
describe_pet(name='harry', type='hamster')
  • Default Values


def describe_pet(name, type='dog'): 
    print("My {}'s name is {}.".format(type,name))

describe_pet(name='willie')




My dog's name is Willie.

describe_pet(name='harry', type='hamster') 
#The default value has been ignored.
  • The following function calls have the same output.


# A dog named Willie.
describe_pet('willie')
describe_pet(name='willie')

# A hamster named Harry.
describe_pet('harry', 'hamster')
describe_pet(name='harry', type='hamster')
describe_pet(type='hamster', name='harry')
  • Making an Argument Optional


def show_name(first, middle, last):
    full_name=first+' '+middle+' '+last
    print(full_name.title())

show_name('john','lee','hooker')

def show_name(first, last, middle=''):
    if middle:
        full_name=first+' '+middle+' '+last
    else:
        full_name=first+' '+last
    print(full_name.title())

show_name('jimi', 'hendrix')

Fruitful functions and void functions

  • Some of the functions yield results, fruitful fucntions

    Some of the functions do not return a value, void fucntions

  • To return a result from a function, we use the return statement in our function.

  • Return means the termination of a function. If you have two returns, only the first one will take effect.

  • 
    def addtwo(a, b):
        added = a + b
        return added 
    # if only return, then it will return None.
    
    x = addtwo(3, 5)
    print(x)
    
    
    def addtwo(a, b):
        added = a + b 
    
    x = addtwo(3, 5)
    print(x)
    
    
    None
    
  • Return and Print


def addtwo(a, b):
    added = a + b 
    print(added)

x = addtwo(3, 5)
print(x)

8
None

def addtwo(a, b):
    added = a + b 
    print(added)
    return added

x = addtwo(3, 5)
print(x)

8
8
  • If we want to return multiple values, the function return a tuple.


def addtwo(a, b):
    added = a + b
    return a, b, added

x = addtwo(3, 5)
print(x)

(3, 5, 8)
  • A function can return any kind of value you need it to, including more complicated data structures like lists and dictionaries.


def build_person(first, last):
    person = {1: first, 2: last}
    return person

musician = build_person('jimi', 'hendrix')
print(musician)

{1: 'jimi', 2: 'hendrix'}

Summary

  • Tuples, Functions
  • Reading: Python for Everybody
    • Tuples Chapter 10.1-10.5, 10.7-10.8
    • Functions Chapter 4