0% found this document useful (0 votes)
48 views25 pages

Unit 5

This document summarizes key concepts about functions, tuples, lists, and mutability in Python. It discusses how functions can be used to decompose programs into reusable structures and abstract away details. It then explains tuples as immutable ordered sequences that can hold mixed data types, and lists as mutable ordered sequences that allow changing element values. The concepts of aliasing, mutability, and cloning lists are also covered.

Uploaded by

Sudarshan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views25 pages

Unit 5

This document summarizes key concepts about functions, tuples, lists, and mutability in Python. It discusses how functions can be used to decompose programs into reusable structures and abstract away details. It then explains tuples as immutable ordered sequences that can hold mixed data types, and lists as mutable ordered sequences that allow changing element values. The concepts of aliasing, mutability, and cloning lists are also covered.

Uploaded by

Sudarshan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Unit 5

§ functions
§ decomposition – create structure
§ abstraction – suppress details
§ Projects and assignment will based
on functions and object oriented

2
6.0001 LECTURE5 2
TODAY
§ We know scalar variable types: int, float,
bool,string
§ introduce some compound data types
§ Tuples
§ lists
§ Also will cover the concept of
§ Aliasing
§ Mutability
§ cloning 3
6.0001 LECTURE5 3
§ an ordered sequence of elements, can mix element types
§ cannot change element values, immutable
§ represented with parentheses
t = ()
t = (2,"MENG",3)
t[0] à evaluates to 2
(2,"MENG",3)+ (5,6) à evaluates to (2,"MENG",3,5,6)
t[1:2] à slice tuple, evaluates to ("MENG",)
t[1:3] à slice tuple, evaluates to ("MENG",3)
len(t) à evaluates to 3
t[1] = 4 à gives error, can’t modify object 4
6.0001 LECTURE5 4
§ conveniently used to swap variable values
x = y temp = x (x, y) = (y, x)
y = x x = y
y = temp
§ used to return more than one value from a function
def quotient_and_remainder(x, y):
q = x // y #integer division operator

r = x % y
return (q, r)
(quot, rem) = quotient_and_remainder(4,5)
5
6.0001 LECTURE5 5
aTuple:(( ),( ),( ))
§ can iterate over tuples

def get_data(aTuple):
nums( )
nums = () words( ? ? ?)
words = ()
if not already in words
for t in aTuple:
i.e. unique strings from aTuple
nums = nums + (t[0],)
if t[1] not in words:
words = words + (t[1],)
min_n = min(nums)
max_n = max(nums)
unique_words = len(words)
return (min_n, max_n, unique_words)
6
6.0001 LECTURE5 6
§ ordered sequence of information, accessible by index
§ a list is denoted by square brackets, []
§ a list contains elements
• usually homogeneous (ie, all integers)
• can contain mixed types (not common)
§ list elements can be changed so a list is mutable

7
6.0001 LECTURE5 7
a_list = []
L = [2, 'a', 4, [1,2]]
len(L) à evaluates to 4
L[0] à evaluates to 2
L[2]+1 à evaluates to 5
L[3] à evaluates to [1,2], another list!
L[4] à gives an error
i = 2
L[i-1] à evaluates to ‘a’ since L[1]='a' above
8
6.0001 LECTURE5 8
MUTABLE
§ assigning to an element at an index changes the value

L = [2, 1, 3]
L[1] = 5
§ L is now [2, 5, 3], note this is the same object L

L
9
6.0001 LECTURE5 9
§ compute the sum of elements of a list
§ common pattern, iterate over list elements
total = 0 total = 0
for i in range(len(L)): for i in L:
total += L[i]
total += i
print total print total
§ notice
• list elements are indexed 0 to len(L)-1
• range(n) goes from 0 to n-1
10
§ to combine lists together use concatenation, + operator,
to give you a new list

L1 = [2,1,3]
L2 = [4,5,6]
L3 = L1 + L2 à L3 is [2,1,3,4,5,6]
L1, L2 unchanged

11
§ L.append(element)
§ add elements to end of list with mutates the list!
L1 = [2,1,3]
L1.append(5 à Lis now [2,1,3,5]
)

§ L.extend(some_list)
§ extend list by add other list to the end (similar to ‘+ ‘)
L1.extend([0,6])à mutated L1 to [2,1,3,0,6]

12
§del(L[index])
§delete element at a specific index with
§L.pop()
§remove element at end of list with, returns the
removed element
§ L.remove(element)
§ remove a specific element with looks for the element
and removes it
• if element occurs multiple times, removes first occurrence
• if element not in list, gives an error

13
§ L = [2,1,3,6,3,7,0]
§ # do below in order

§ L.remove(2) à mutates L = [1,3,6,3,7,0]


§ L.remove(3) à mutates L = [1,6,3,7,0]

§ del(L[1]) à mutates L = [1,3,7,0]


§ L.pop() à returns 0 and mutates L = [1,3,7]

14
§list(s)
§convert string to list with, returns a list with every character
from s an element in L
§s.split(),
§can use to split a string on a character parameter, splits on
spaces if called without a parameter
§''.join(L)
§to turn a list of charactersinto a string, can give a character
in quotes to add char between every element

15
s = "I<3 MENG" à s is a string
list(s) à returns ['I','<','3',' ','M', ‘E', ‘N’, ‘G']
s.split('<') à returns ['I','3 MENG']

16
L = ['a','b','c'] à L is a list
''.join(L) à returns "abc"
'_'.join(L) à returns "a_b_c"

16
§ sort() and sorted()
§reverse()
§and many more
https://docs.python.org/3/tutorial/datastructures.html

L=[9,6,0,3]
sorted(L) à returns sorted list, does not mutate L
L.sort() à mutates L=[0,3,6,9]
L.reverse() à mutates L=[9,6,3,0]
17
§ lists are mutable
§ behave differently than immutable types
§ is an object in memory
§ variable name points to object
§ any variable pointing to that object is affected
§ key phrase to keep in mind when working with lists is
side effects

18
§ hot is an aliasfor warm – changing one changes the
other.
§ append() has a side effect

19
§ create a new list and copy every element using
chill = cool[:]

20
20
§ calling sort() mutates the list, returns nothing
§calling sorted()
does not mutate
list, must assign
result to a variable

21
§can have nested lists
§side effects still
possible after mutation

22
l1=[1,2,3] l1=[1,2,3]
l2=[l1,l1] l2=[l1[:],l1[:]]
l1.append(4) l1.append(4)
print (l2) print (l2)

23
§ avoid mutating a list as you are iterating over it
def remove_dups(L1, L2): def remove_dups(L1, L2):
for e in L1: L1_copy = L1[:]
if e in L2: for e in L1_copy:
L1.remove(e) if e in L2:
L1.remove(e)
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
remove_dups(L1, L2)
§ L1 is [2,3,4] not [3,4] Why?
• Python uses an internal counter to keep track of index it is in the loop
• mutating changes the list length but Python doesn’t update the counter
• loop never sees element 2
24
X=(1,[2,3]) X=[1,(2,3)]
X[1][0]=10 X[1][0]=10
print (X) print (X)

X=(1,[2,3]) X=[1,(2,3)]
X[1]=10 X[1]=10
print (X) print (X)

25

You might also like