202 Lec18 Obj2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

COMP 202

Lecture 18

Objects II

Fall 2022
slides by Giulia Alberini and Jonathan Campbell
© Instructor-generated course materials (e.g., slides, notes, assignment or exam questions, etc.) are protected by law and may not
be copied or distributed in any form or in any medium without explicit permission of the instructor. Note that infringements of
copyright can be subject to follow up by the University under the Code of Student Conduct and Disciplinary Procedures.
Announcements
• "D" groups presenting today (A/B/C giving feedback)

• A2 due this evening.

• Please search before posting on discussion board.

• A2 code review meetings will be held in week(s) after midterm.

• Submit PQ3 w/ 50%+ by next Wed @ 1 p.m. for coins.

• Midterm topics posted to help in your review.

• Practice exams will be posted this by this weekend.

2
Plan for today

• Objects

• Recap of objects and computer memory

• Object ID

• Identity operators

• Mutability

3
Objects
Recall: variables

Computer memory
city = "Montreal"
population = 1704694
area = 431.50 city "Montreal"

population 1704694
After this code is run,
three variables are created
area 431.50
which refer to their
corresponding values

5
Object references

• What is actually happening when a variable assignment


is executed?

• An object is created

• a value is assigned to it, and

• a reference to the object is stored in the variable

• Python is a highly object oriented programming language.


Every piece of data in Python is an object of a speci c type.

6
fi
Example
Computer memory

"cat"

a 5
>>> a = 5
b 3
>>> b = a

>>> b = 3

>>> a = "cat" The value 5


has no more arrows
(references) pointing to it!
It gets garbage collected
(removed from memory).
7
The life of an object

• Creation

• Manipulation (while it exists)

• Stops existing when there are no more references to it.


Garbage collection will reclaim the memory space.

8
Object ID
Object ID

• Each object is assigned an identi er at its creation


(its memory address).

• This identity is unique and constant for the object


during its lifetime (it never changes).

10
fi
Object identity

• The built-in function id() returns the identity of an


object. (This function is generally used internally in
Python.)

>>> weather_str = "It's raining"


>>> print(id(weather_str))
4449231792

>>> secret_num = 1.5462


>>> print(id(secret_num))
4449109456

11
Example
Computer memory
• What do you expect to see
when the following program
executes?
x 500
>>> x = 500
>>> y = x y
>>> id(x) == id(y)
True

x and y both point to the same object,


therefore their IDs are the same.

12
Example
Computer memory
• What do you expect to see
when the following program
executes?
x 500
>>> x = 500
>>> y = 400 y 400
>>> id(x) == id(y)
False

x and y point to two di erent objects,


therefore we expect x and y to have di erent IDs.

13
ff
ff
Example
Computer memory
• What do you expect to see
when the following program
executes?
x 500
>>> x = 500
>>> y = 500 y 500
>>> id(x) == id(y)
False

x and y point to two di erent objects


(with the same value, but di erent!),
therefore we expect x and y to have di erent IDs.

14
ff
ff
ff
Identity operators
is and is not

• is and is not are boolean operators used to determine


if the given operands have the same identity (i.e., refer to
the same object)

• Note that this is not the same thing as checking for


equality! When two operands are equal via ==, it means
that they refer to objects that contain the same data, but
they don't necessarily refer to the same object.

16
Examples

>>> x = 500
>>> x = 500 >>> x = 500 >>> y = 300
>>> y = 500 >>> y = 500
>>> z = x >>> z = x >>> x is y
False
>>> x == y >>> x is y
True False >>> x == y
False
>>> x == z >>> x is z
True True >>> x is not y
True

17
Aside: a corner case

• While it's true that a new object is created each time we


assign a value to a variable, there are a few exceptions.
Moreover, depending if you execute your code in the shell
or through a program, you might see a di erent output.

• In the shell, for purposes of optimization, objects for the integers in


the range [-5, 256] are created at startup, and then reused when
executing code. Thus, when you assign separate variables to an
integer value in this range, they will actually reference the same
object. This also happens for some strings.

18
ff
Corner case - examples

>>> x = 5 >>> x = 'cat'


>>> y = 5 >>> y = 'cat'
>>> id(x) == id(y) >>> id(x) == id(y)
True True

19
Aside: another corner case

• While it's true that a new object is created each time we


assign a value to a variable, there are a few exceptions.
Moreover, depending if you execute your code in the shell
or through a program, you might see a di erent output.

• In a module, Python uses caching for almost all immutable objects


of a built-in type. So if you assign separate variables to an
immutable object (ints or strings for examples) with the same value,
they will actually reference the same object.

20
ff
Corner case 2 - example
x = 500
y = 500
print(id(x) == id(y))
f = 5.5
g = 5.5
print(id(f) == id(g))
s = "Every time I learn something new, it pushes \
some old stuff out of my brain. - Homer"
t = "Every time I learn something new, it pushes \
some old stuff out of my brain. - Homer"
print(id(s) == id(t))

If you try all of the above instructions in the shell you'll see False displayed.
If you run the module, all print statements will display True.

21
Mutable vs immutable
Mutable vs immutable

• There are two types of objects:

• Immutable: the content of the object cannot be changed after the


object has been created.

• Mutable: the content of the object can be changed after the


object has been created (without changing its identity).

23
Strings: immutable

• Strings are immutable objects.

• We cannot use the square brackets


to modify a character in the string,
like for instance we do with lists.

>>> s = "cats"
>>> s[0] = 'r'
TypeError

24
Example
s = "cat"
t = s
print("Before", id(s) == id(t))
s = s.replace('c','r')
print("After", id(s) == id(t))
print("s:", s)
print("t:", t)

What prints?
Before True
After False
s: rat
t: cat
25
Copying lists
x = [1, 2, 3]
y = x

• These statements create a list of three integers and make two


di erent variables, x and y, refer to it.

• Any changes to the elements made by either variable


will be seen through the other.

• Because x and y are di erent names for the same thing,


they are sometimes called aliases.

• If you actually want to copy the list, not just a reference,


you need to create a new list.

26
ff
ff
Example of mutability with lists
Computer memory

0 5

>>> x = [5, 6, 7] x 1 6

2 7
y = x

y[0] += 1

print(x[0], y[0])

27
Example of mutability with lists
Computer memory

0 5

x = [5, 6, 7] x 1 6

2 7
>>> y = x y

y[0] += 1

print(x[0], y[0])

28
Example of mutability with lists
Computer memory

0 6

x = [5, 6, 7] x 1 6

2 7
y = x y

>>> y[0] += 1

print(x[0], y[0])

29
Example of mutability with lists
Computer memory

0 6

x = [5, 6, 7] x 1 6

2 7
y = x y

y[0] += 1

>>> print(x[0], y[0])

6 6
30
Example of mutability with lists (2)
Computer memory

0 5

def example(x): x 1 6

2 7
x[0] = x[0] * 5

>>> x = [5, 6, 7]

example(x)

print(x[0])

31
Example of mutability with lists (2)
Computer memory

0 5

def example(x): x 1 6

2 7
x[0] = x[0] * 5

x = [5, 6, 7]

>>> example(x)

print(x[0])

32
Example of mutability with lists (2)
Computer memory

0 5

>>> def example(x): x 1 6


GLOBAL
2 7
x[0] = x[0] * 5

x
x = [5, 6, 7] LOCAL

example(x)

print(x[0])

33
Example of mutability with lists (2)
Computer memory

0 5

>>> def example(x): x 1 6


GLOBAL
2 7
x[0] = x[0] * 5

x
x = [5, 6, 7] LOCAL

example(x)
Note: The two x variables are not the
print(x[0]) same variable. However, they do refer
to the same list.

34
Example of mutability with lists (2)
Computer memory

0 25

def example(x): x 1 6
GLOBAL
2 7
>>> x[0] = x[0] * 5

x
x = [5, 6, 7] LOCAL

example(x)

print(x[0])

35
Example of mutability with lists (2)
Computer memory

0 25

def example(x): x 1 6
GLOBAL
2 7
x[0] = x[0] * 5

x = [5, 6, 7]

example(x)

>>> print(x[0])

25
36
Example of mutability with lists (2)

def example(y):
To stress that the two
variables are not the same,
y[0] = y[0] * 5 we can for instance change
the name of the parameter in
x = [5, 6, 7] the function example.

The program will work the


example(x)
same as before.

print(x[0])

37
Recall: increasing by index

• A function that takes a list of integers as input and


increases the value of each element in the list by its index.

def increase_by_index(input_list):
for i in range(len(input_list)):
input_list[i] = input_list[i] + i

return input_list
Is this really
necessary?

38
Try it!

• Write a void function that takes as input a list and two


integers i and j. The function should swap the two
elements of the list that are in position i and j.

• Write a void function that takes a list as input and


modi es it so that all the elements are moved up by one
position.

39
fi
Lists vs strings
pets = ["cat", "dog"]

"cat"
0

pets
1

"dog"

40
Lists vs strings
pets = ["cat", "dog"]
pets[0] = pets[0].replace('c', 'r')

"cat"
0

pets
"rat"
1

"dog"

Note that we changed the list.


Lists are mutable so the reference
(arrow) in pets did not change.

41
Lists vs strings
pets = ["cat", "dog"]
pets[0] = pets[0].replace('c', 'r')

"cat"
0

pets
"rat"
1

"dog"

Note that we changed the list. However, strings are immutable. Strings
Lists are mutable so the reference in memory can never be changed. When
(arrow) in pets did not change. we changed the rst string, the reference
(arrow) in pets[0] did change.
42
fi
Lists vs strings - Example
def my_function(a):
for i in range(len(a)):
a[i] = i

x = [1, 2, 3, 4]
my_function(x)
print(x)

What prints?

[0, 1, 2, 3]

43
Lists vs strings - Example

def my_function(t):
t = t.replace('c', 'r')

s = "cat"
my_function(s)
print(s)

What prints?

cat

44
Lists vs strings - Example
letters = ['w', 'o', 'r', 'd']
for i in range(len(letters)):
if letters[i] == 'o':
letters[i] = 'a'

print(letters)

What prints?

['w', 'a', 'r', 'd']

45
Lists vs strings - Example

s = "word"
for i in range(len(s)):
if s[i] == 'o':
s[i] = 'a'
print(s)

What prints?

TypeError: 'str' object does


not support item assignment

46
Lists vs strings - Example
s = "word"
t = ""
for i in range(len(s)):
if s[i] == 'o':
t = t + 'a'
else:
t = t + s[i]

print(t)

47
What modi es a list?

• Which of the operators/methods we have seen


modify the content of a list object?

• Assigning a value to an element using its index.

a = [1, 2, 3]
a[0] = 5 # the reference in a has not changed
# the list referenced by a has changed

• Using slice assignment to modify the elements of a list.

a = [1, 2, 3]
a[:2] = [5] # as above, the reference in a has not changed
# the list referenced by a has changed.

• Using methods like append(), insert(), remove(), pop() or sort().

48
fi
What modi es a list?
• Which of the operators/methods we have seen
modify the content of a list object?

• For lists only, the += operator works like append().

a = [1, 2, 3]
print(id(a)) # 4451399808
a += [4, 5]
print(id(a)) # 4451399808

a = [5, 6, 7]
print(id(a)) # 4457416576
a.append(4)
a.append(5)
print(id(a)) # 4457416576

49
fi
What does not modify a list?
• Which of the operators we have seen
do not modify the content of a list object?

• Slicing! It is a useful tool to create new lists out of an existing lists.

a = [1, 2, 3]
b = a[:] # makes a copy of a
print(a is b) # False! The two variables refer
# to different objects.

• The + and * operators!

a = [1, 2, 3]
b = a
b = b + [4] # b now refers to a new list [1, 2, 3, 4]
# a still references the list [1, 2, 3]

50
Resources

• Think Python 2e
http://greenteapress.com/thinkpython2/thinkpython2.pdf

Sections 10.10-10.11

51
Coming up

• Next lecture:

• Nested lists

52

You might also like