Exercises

These exercises check whether you can choose containers and transform small data.

Exercise: Append to a list

What does this print?

Answer it first, then check.

Hint

append() adds one item at the end of the existing list.

Solution

The list starts as:

["a"]

After append("b"), it becomes:

["a", "b"]

Python prints string quotes with single quotes in this list display:

['a', 'b']
Exercise: Tuple unpacking

What is the value of field?

Answer it first, then check.

Hint

The second name receives the second tuple value.

Solution

Unpacking assigns from left to right:

name, field = ("Ada", "math")

So field is:

math
Exercise: Fix the counter

Edit the code so the output contains 'cat': 2.

Count with a dictionary

Runs locally with Python in your browser.

Ready to run.

Hint

When a word already exists, use its old count and add one.

Solution

One fix is:

The first "cat" creates the count. The second "cat" increments it.

Exercise: Set membership

What does this print?

Boolean

Select one choice, then check.

Hint

Membership checks produce booleans.

Solution

seen contains "red" and "blue", not "green".

The expression:

"green" in seen

produces:

False
Exercise: Copy before mutating

Edit the code so the output contains a: [1, 2] and b: [1, 2, 3].

Make a separate list

Runs locally with Python in your browser.

Ready to run.

Hint

Use .copy() when assigning b.

Solution

Use .copy():

Output:

a: [1, 2]
b: [1, 2, 3]

Now a and b refer to different list objects.