Post

Objects, Names, and Collections in Python

Correcting a participant’s scores may require a working copy alongside the recorded values. In Python, however, giving a list a second name does not create a separate list: a change through either name can alter the same scores. We therefore need to understand what names refer to before deciding how to make a correction. This chapter begins with individual values and lists, examines assignment and copying, and then organizes related values into records. We also distinguish an operation’s return value from any change it makes to the original object.

3.1 Values, types, and elementary operations

In Python, every value is an object with a type. type() distinguishes the integer 90, the floating-point number 90.0, and the string of characters "90". What do you expect + to do in 90 + 10 and in "90" + "10"?

1
2
3
type(90)
type(90.0)
type("90")
1
2
3
<class 'int'>
<class 'float'>
<class 'str'>

With two integers, + adds their values. With two strings, it joins the characters end to end, an operation called concatenation.

1
2
90 + 10
"90" + "10"
1
2
100
'9010'

If a duration arrives as the text "90", int(duration_text) returns the integer 90 for the addition. The name duration_text still refers to the string. The same conversion turns the identifier "0007" into 7, which no longer shows the four digits recorded for that participant.

1
2
3
4
5
duration_text = "90"
int(duration_text) + 10
duration_text
type(int(duration_text))
int("0007")
1
2
3
4
100
'90'
<class 'int'>
7

For these numbers, == compares values and returns a Boolean, either True or False. A single = is used for assignment. The integer 90 and the floating-point number 90.0 have equal values despite their different types.

1
2
3
90 == 90.0
90 == 100
type(90 == 90.0)
1
2
3
True
False
<class 'bool'>

In this example, None marks an unavailable answer. It is a single object of type NoneType. The is operator tests identity, meaning whether two expressions refer to the same object. Entering answer alone displays nothing when its value is None. The first True below comes from answer is None.

1
2
3
4
5
6
answer = None
answer
answer is None
duration = 90
duration is None
type(None)
1
2
3
True
False
<class 'NoneType'>

bool() gives an object’s truth value, the True or False Python uses for a yes-or-no decision. Can that test tell a measured duration of zero from a missing duration?

1
2
3
4
5
6
bool(0)
bool(False)
bool("")
bool(None)
bool(90)
bool("0")
1
2
3
4
5
6
False
False
False
False
True
True

The first four objects all give False, although they mean different things. Zero can be a measured duration, False can be a recorded answer, an empty string contains no characters, and None marks an unavailable value. The string "0" is nonempty and gives True. is None tests for the chosen absence marker specifically, so a recorded zero can still count as a measurement.

3.2 Lists, positions, and slices

In scores = [2, 4, 5], the scores form a list, an ordered collection. The visit order lets you retrieve the first score for a calculation or take the first two together. Commas separate the items inside the brackets. Each position refers to an object, here an integer. This link is called a reference. len(scores) counts the items.

1
2
3
4
scores = [2, 4, 5]
scores
len(scores)
type(scores)
1
2
3
[2, 4, 5]
3
<class 'list'>

An integer in brackets after the list selects the item at that position. This integer is called an index. Python counts from 0, so the three scores have indexes 0, 1, and 2.

1
scores[0]
1
2

A negative index counts from the end, so scores[-1] retrieves the last item. This works for any nonempty list without first finding its length.

1
scores[-1]
1
5

Slicing a list returns a new list for a range of positions. In scores[0:2], the start is included and the stop is excluded, so the result contains the items at indexes 0 and 1.

1
scores[0:2]
1
[2, 4]

scores[0] retrieves the first score as an integer. The slice scores[0:1] returns a list containing that same score. Which result can you add 1 to?

1
2
3
4
5
6
7
first = scores[0]
first_slice = scores[0:1]
first
first_slice
type(first)
type(first_slice)
first + 1
1
2
3
4
5
2
[2]
<class 'int'>
<class 'list'>
3
1
2
# Deliberate error: adding a number to a list
first_slice + 1
1
TypeError: can only concatenate list (not "int") to list

first + 1 gives 3. The addition to first_slice fails because list addition joins two lists, and 1 is an integer.

The same operators therefore describe different operations on a list and on a score. scores + [3, 1] concatenates two lists. Multiplying a list by an integer repeats its items in order, so scores * 2 repeats the three scores rather than doubling each score.

1
2
scores + [3, 1]
scores * 2
1
2
[2, 4, 5, 3, 1]
[2, 4, 5, 2, 4, 5]

Both operations return new lists and do not change scores.

1
scores
1
[2, 4, 5]

3.3 References, mutation, and copying a list

Suppose a working list needs its first score changed from 2 to 3 while the recorded values [2, 4, 5] must be unchanged. Will assigning the list a second name protect those scores?

In working = scores, a second name refers to the existing list. Like a list position, a name stores a reference. The is test checks whether both names refer to the same object.

1
2
3
4
5
scores = [2, 4, 5]
working = scores
scores
working
working is scores
1
2
3
[2, 4, 5]
[2, 4, 5]
True

An index on the left of = identifies the list item to replace. In working[0] = 3, that item is the first score.

1
2
3
working[0] = 3
scores
working
1
2
[3, 4, 5]
[3, 4, 5]

Both names show [3, 4, 5] because working[0] = 3 changed the list they share. A change to an existing object is called mutation.

The assignment working = [9] makes working refer to a different list. This is called rebinding. The list named scores still starts with 3.

1
2
3
working = [9]
scores
working
1
2
[3, 4, 5]
[9]

For a fresh comparison, scores = [2, 4, 5] creates a new list with the recorded values. The list’s copy() method, a function called through the list, returns a separate list with the same items. The is test checks whether the two names refer to one list. The == test compares their contents.

1
2
3
4
scores = [2, 4, 5]
working = scores.copy()
working is scores
working == scores
1
2
False
True

False for is and True for == mean that the two lists are distinct and contain equal scores. The replacement working[0] = 3 now acts on the copy.

1
2
3
working[0] = 3
scores
working
1
2
[2, 4, 5]
[3, 4, 5]

The original still starts with 2 because we replaced an item in the copy. What if that item is itself a list? In nested_copy[0][0] = 3, the first [0] retrieves the inner list and the second [0] identifies the score to replace in it.

1
2
3
4
5
6
nested = [[2, 4], 5]
nested_copy = nested.copy()
nested_copy[0] is nested[0]
nested_copy[0][0] = 3
nested
nested_copy
1
2
3
True
[[3, 4], 5]
[[3, 4], 5]

The True from nested_copy[0] is nested[0] shows that the two outer lists refer to the same inner list. Only the outer list was copied, so changing the first score in the inner list makes 3 appear in both displays.

3.4 Tuples, dictionaries, and records

How can you retrieve the duration from a response record? In this example, the three fields are the participant ID "0007", the duration of 90 seconds, and the completion flag True. A tuple stores these values in order. In record = ("0007", 90, True), record[1] retrieves the duration because it comes second. Unpacking with participant_id, duration, completed = record assigns the items in order, one name per item.

1
2
3
4
5
6
7
8
record = ("0007", 90, True)
record
type(record)
record[1]
participant_id, duration, completed = record
participant_id
duration
completed
1
2
3
4
5
6
('0007', 90, True)
<class 'tuple'>
90
'0007'
90
True

Can record[1] = 120 correct the duration in this tuple?

1
2
# Deliberate error: replacing a tuple item
record[1] = 120
1
TypeError: 'tuple' object does not support item assignment

A tuple is immutable, so its items cannot be replaced after it is created. In the tuple paired below, the second item is a list. In paired[1][0] = 3, paired[1] retrieves that list and the final [0] selects the score to replace inside it.

1
2
3
paired = ("0007", [2, 4, 5])
paired[1][0] = 3
paired
1
('0007', [3, 4, 5])

The tuple’s second item is still the same list. Changing a score inside that list does not replace the tuple item.

A dictionary makes it possible to retrieve the duration by name. It stores values under unique keys. In this record, each key is a string naming a field. Inside {}, a colon separates each key from its value, and len(response) counts the keys.

1
2
3
4
response = {"participant_id": "0007", "duration": 90, "completed": True}
response
type(response)
len(response)
1
2
3
{'participant_id': '0007', 'duration': 90, 'completed': True}
<class 'dict'>
3

In response["duration"], the string "duration" is the key. The value it retrieves is the integer 90.

1
2
3
response["duration"]
type("duration")
type(response["duration"])
1
2
3
90
<class 'str'>
<class 'int'>

For a dictionary, in tests whether a key is present. The record contains "duration" but no "answer" key. Looking up the missing key with response["answer"] raises KeyError.

1
2
"duration" in response
"answer" in response
1
2
True
False
1
2
# Deliberate error: looking up an absent key
response["answer"]
1
KeyError: 'answer'

An answer field can also exist with an unavailable value. with_answer = response.copy() copies the three fields. Assigning None to with_answer["answer"] adds a fourth field to that copy. The expression "answer" in with_answer tests whether the field exists, and with_answer["answer"] is None tests its value.

1
2
3
4
5
6
7
with_answer = response.copy()
with_answer["answer"] = None
with_answer
response
"answer" in with_answer
with_answer["answer"] is None
with_answer["duration"]
1
2
3
4
5
{'participant_id': '0007', 'duration': 90, 'completed': True, 'answer': None}
{'participant_id': '0007', 'duration': 90, 'completed': True}
True
True
90

A dictionary’s get() method returns the value for a key. If the key is absent, it returns None unless a second argument specifies another default. Will response.get("answer") and with_answer.get("answer") return different values?

1
2
response.get("answer") is None
with_answer.get("answer") is None
1
2
True
True

Both tests evaluate to True. The first get() returns None because response has no "answer" key. The second returns None because that is the value stored under "answer". A test with in distinguishes those two records because it looks for the key itself.

3.5 Attributes, methods, and namespaces

If you want a copy of scores, do you write scores.copy or scores.copy()? An attribute is a value accessed by name through an object. The dot retrieves the list’s copy method. Adding the parentheses calls that method, which returns a new list. The two type() calls distinguish the method from its result.

1
2
3
4
5
scores = [2, 4, 5]
type(scores.copy)
copied = scores.copy()
type(copied)
copied
1
2
3
<class 'builtin_function_or_method'>
<class 'list'>
[2, 4, 5]

A method can also change an existing list. Whereas copy() returns a separate list, measurements.append(3) adds 3 to the end of measurements.

1
2
3
measurements = [2, 4, 5]
measurements.append(3)
measurements
1
[2, 4, 5, 3]

The Console displayed [2, 4, 5, 3] when it evaluated measurements on the following line. What did measurements.append(3) itself return? Assigning the next call to result lets you check.

1
2
3
result = measurements.append(1)
result is None
measurements
1
2
True
[2, 4, 5, 3, 1]

The True from result is None shows that measurements.append(1) returned None. The 1 at the end of measurements shows that the same call changed the list. At the Console, the call alone displays no return value.

Strings cannot change in place. For the recorded label " Female ", strip() returns the text without the spaces at its ends. More generally, it removes leading and trailing whitespace, including tabs and line breaks. Spaces between words are unaffected.

1
2
3
4
label = " Female "
trimmed = label.strip()
trimmed
label
1
2
'Female'
' Female '

trimmed is "Female", and label still includes the surrounding spaces. The lower() method returns the lowercase text "female". The trimming and lowercasing can also be written as one expression, label.strip().lower().

1
2
3
trimmed.lower()
label.strip().lower()
label
1
2
3
'female'
'female'
' Female '

The dot also retrieves functions from a module. A module has its own namespace, the names it defines and the objects they refer to. import math adds math to the session without adding a separate name for sqrt. In math.sqrt(9), the dot looks up the square-root function in the module, and the parentheses call it with the number 9.

1
2
3
4
import math
type(math)
math.sqrt(9)
type(math.sqrt(9))
1
2
3
<class 'module'>
3.0
<class 'float'>

Table 3.1 shows what each call returns and whether it changes the object before the dot. In label.strip().lower(), lower() runs on the string returned by strip(). Chaining another append() directly to measurements.append(1) would fail because the first call returns None, which has no append method.

Table 3.1. Return values and changes to the original objects in five Python calls.

CallObject before the dotAttributeReturned objectDid the call change the original object?
scores.copy()list scorescopynew list [2, 4, 5]no
measurements.append(1)list measurementsappendNoneyes
label.strip()string ' Female 'stripstring 'Female'no
trimmed.lower()string 'Female'lowerstring 'female'no
math.sqrt(9)module mathsqrtfloat 3.0no
This post is licensed under CC BY-NC 4.0 by the author.