Lecture 1.2

Collections and Control Flow

Python and Big Data in Economics

Guoliang Ma
The Chow Institute, 2025

What you will learn

Very elementary Python theory

More building blocks and more functions

Control flow (for loop and if condition)

If we liken a program to a building, the variables are blocks and syntax tells the programmer how to put the blocks together to form walls. Different programs are just different ways to put the walls together.

1.2.3 Mapping — dictionary

Lists and tuples select elements by position: items[0], items[1], and so on.

A dictionary selects a value by its key. Keys can be strings or other hashable objects; they are not restricted to names.

The dictionary stores key–value pairs.

1.2.3 Mapping — dictionary

Example 1.2.3.1 ways to create a dictionary

age = {"Alice": 21,
       "Bob": 32,
       "Charlie": 44}
name = dict(stu1="Alice",
            stu2="Bob",
            stu3="Charlie")
grade = dict([['stu1', 87],
              ['stu2', 99],
              ['stu3', 65]])
dict.fromkeys(["key1", "key2"], ...)

1.2.3 Mapping — dictionary

Dictionary entries consist of keys and values. Look up a value by passing its key, as in age["Alice"].

If the key is absent, subscription raises KeyError. The get() method instead returns a default value (None unless you supply another value).

In-class exercise 1.2.3.1

What are the keys and values in the three dictionaries on the previous slide?

1.2.3 Mapping — dictionary

Taking out elements by subscripting

Error handling and the get function

age[Alice]
age["Alice"]
l = [1, 2, 3]
l[3]
age["David"]

Special topic: Flow control (I) — for loop

How can we access all the elements in a list one by one?

We could take them out manually by l[0], l[1], l[2], etc.

We could create an index variable i to help us:

A more convenient way it to rely on the automated for-loop

l = [1, 2, 3]
i = 0
l[i]
i = 1
l[i] # note: notebook cells can display a final expression without print
for element in container:
    ...

Special topic: Flow control (I) — for loop

In-class exercise Special (I).1

Make a list and use for loop to print its elements

Make a tuple and use for loop to print its elements

Make a dictionary and use for loop to print its values

Make a dictionary and use for loop to print its keys

Print the key-value pairs in a formatted way using the f-string

Special topic: Flow control (I) — for loop

We informally introduce a useful function for for-loops: range

range is very similar to slices

range(10)
range(1, 11)
range(0, 30, 5)
range(0, 10, 3)
range(0, -10, -1)
range(0)
range(1, 0)

Special topic: Flow control (I) — if statement

There are circumstances when we only want to print out certain elements of a list/a tuple/a dictionary.

For example, given a list

We only need the numbers that are squares of some integer. Or we only need the numbers that are cubics of some integers. Or just odd numbers.

In other words, only if the element satisfy a condition.

Here we use the if control flow

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
if element % 2 == 0:
    ...

Special topic: Flow control (I) — if statement

In-class exercise Special (I).2

For the list containing 13 elements

Print elements that are odd

Print elements that are squares

Print elements that are cubics

Special topic: Flow control (I) — if statement

== vs. is

In the if-statement, the most commonly used condition is comparisons

compare the values two numbers by magnitude: <, >, ==

compare the identity: is

None is a special object in Python. Investigate it.

Special topic: Flow control (I) — if statement

Comparison expressions return boolean variables. By expression, we refer to Python code that can be evaluated. The formal definition is involved and we will talk about it in future courses. Comparison expressions rely on <, >, <=, >=, != and is and not.

Evaluation of comparisons support chained expressions. For example:

a, b, c, d, e = 1, 4, 3, 3, 5
a < b > c == d != e

Comparisons with None

None is Python’s singleton object used to represent the absence of a value.

Use is None or is not None to test for it. Multiple names can refer to that same object.

a = None
b = None
a is b

is compares object identity; == compares values using the type’s equality operation.

1.2.3 Mapping — dictionary

Sometimes we want to add more elements to a dictionary.

We can use the [] operator

Sometimes we want to combine two dictionaries.

We can use the update method.

Read this: https://python-reference.readthedocs.io/en/latest/docs/dict/update.html

1.2.3 Mapping — dictionary

Dictionaries are very different from lists or tuples

Example 1.2.3.3 list differs from dictionary

d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}

for i in d:
    if not d[i]:
        d.pop(i)

d = [1, 2, 3, 0, 5]

for i in range(4):
    if not d[i]:
        d.pop(i)

1.2.3 Mapping — dictionary

Example 1.2.3.4 JSON file as a dictionary

import json

with open("settings.json", "r") as f:
    setting_dict = json.load(f)

setting_dict

setting_dict.items()

1.2.3 Mapping — dictionary

Before we end the discussion of dictionaries, there is one last topic: the zips.

zip, in language means 拉链

As the name suggests, Python zips involve two sequences just as the real-life zippers. For example:

account = ["622848", "600314", "500297"]
balance = (1_000_000, 1_300_500, 500)
z1 = zip(account, balance)

for k, v in z1:
    print(k, "has a balance of", v)

1.2 Objects’ types

In-class exercise 1.2.2

What simple types have we learned?

What complex types have we learned?

How do you tell them apart?

1.2.4 Strings

Quotation marks distinguish string values from variable names. Single and double quotes both delimit strings.

A string is an immutable sequence of Unicode characters. Indexing it produces another string of length one.

Three groups of tools to explore:

  • Case conversion: upper, lower, title.
  • Removing leading/trailing characters: strip, lstrip, rstrip.
  • Pattern replacement: re.sub from the re module.

A module is Python code stored separately for reuse.

1.2.4 String

In-class exercise 1.2.4.1

Reverse a string. For example, given s = “desserts”, reverse it to get “stressed”. Reverse “drawer” to get “reward”. These are known as anadromes.

Remove vowels from a string. For example, “drawer” would become “drwr”.

Count the number of words in a string (using the split method).

1.2.5 Unordered nonduplicate — set

By definition. A set object is an unordered collection of distinct hashable objects: https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset

Python doc provides a glossary page for your reference: https://docs.python.org/3/glossary.html#term-hashable

Set behaves just like the set concept we encounter in math courses. The elements of a set are unique and unordered. We can also use math concepts like in (), issubset (), union (), intersection (), difference (), and symmetric difference (Δ) to work on sets.

In-class exercise 1.2.5.1

How do you check if an object is hashable?

1.2.5 Unordered nonduplicate — set

There are several ways to create a set

Use braces such as {1, 2}; {} alone creates an empty dictionary

Use the set function set()

Use set comprehension (later)

We can modify a set once it's created. See the exercise.

We create a frozenset mainly using frozenset()

1.2.5 Unordered nonduplicate — set

In-class exercise 1.2.5.2

1. Create a set containing the numbers 1, 2, 3, 4, and 5.

2. Add the number 6 to the set.

3. Create two sets: set_a = {1, 2, 3, 4} and set_b = {3, 4, 5, 6}.

4. Find the union of set_a and set_b.

5. Find the intersection of set_a and set_b.

6. Find the difference between set_a and set_b.

7. Find the symmetric difference between set_a and set_b.

8. Given the list numbers = [1, 2, 2, 3, 4, 4, 4, 5]. Create a set to remove duplicate elements.

9. Convert the set back into a list (with fewer elements).

1.3 Pythonic style

Pythonic means writing clear, idiomatic Python. It does not mean every technique is unique to Python.

We have already encountered zip, with, None, sorted, and f-strings.

Next, explore comprehensions and enumerate.

1.3 Pythonics — comprehensions (1)

List comprehension

Set comprehension

Dictionary comprehension

The one missing is "tuple comprehension". But when you write

you do not get a tuple. What do you get?

[x for x in range(5)] # usually faster than list, if not too complicated
{c for c in 'abcdcba'}
{x: x ** 2 for x in range(5)}
(i for i in range(3))

1.3 Pythonics — comprehensions (1)

We can also add the if control flow to comprehensions:

Only the if condition

if condition with else condition

Import time before running the following expressions.

In-class exercise 1.3.1

How long does each of the following code take to run?

[x for x in range(10) if x % 2 == 0]
[x if x % 2 == 0 else x + 1 for x in range(10)]
[time.sleep(1), time.sleep(1), time.sleep(1)][0]
(time.sleep(1), time.sleep(1), time.sleep(1))[0]

1.4 Objects’ values

Let’s step back before the end of this section.

Recall that an object is stored by its (i) id, (ii) type, and (iii) contents

What roles do these components play?

What if “你的打开方式不对?”

type-casting using the name of the type

Type conversion returns an object of the requested type; it does not change the type of the original object. What about changing an object’s value?

When the value change does not alter the address, the name reference is not changed. We say the object and the type of the object is mutable.

Mutable objects are very useful and sometimes tricky. We’ll explore more in the next Chapter.

1.4 Objects’ values

In-class exercise 1.4.1

What types of objects are mutable? How do you verify it?

Further readings/watching