Python + oTree Crash Course

Session II - Python Basics 2

Ali Seyhun Saral (Institute for Advanced Study in Toulouse)

IMPRS Be Smart Summer School

2023-08-07

Lists in Python

  • A list is a collection of items in a particular order.
  • Lists can contain different types of items.
a = [10,20,30]
print(a)
[10, 20, 30]
b = ["ali", "bob", "chiara"]
print(b)
['ali', 'bob', 'chiara']
c = ["ali", 2]
print(c)
['ali', 2]

Reaching into List Items in Python

  • You can access the items in a list using the index.
  • The index starts from 0.
my_list = [ “ali”, “bob”, “chiara”]
0 1 2




my_list[0]
'ali'
my_list[1]
'bob'
my_list[2]
'chiara'

Reaching from the end

  • You can access the items from the end using a negative index starting from -1.
my_list = [ “ali”, “bob”, “chiara”]
-3 -2 -1




my_list[-1]
'chiara'
my_list[-3]
'ali'

List Slicing in Python

  • You can access a subset of a list using the slice operator :.

  • Basic usage

[ start : end]

  • end is not included in the slice.
my_list = ["ali", "bob", "chiara", "dominique", "elizabeth"]
# Get first three items
my_list[0:3] 
['ali', 'bob', 'chiara']
# Get three items starting from 1
my_list[1:4] 
['bob', 'chiara', 'dominique']

List Slicing in Python

  • If you leave the index empty, python will take from the beggining/end.
my_list = ["ali", "bob", "chiara", "dominique", "elizabeth"]
# From the beginning until the index 4
my_list[:4] 
['ali', 'bob', 'chiara', 'dominique']
# From index 1 until the end
my_list[1:] 
['bob', 'chiara', 'dominique', 'elizabeth']

Updating List Items in Python

  • You can update the items in a list using the index.
my_list = ["ali", "bob", "chiara"]

my_list[0] = "alice"
print(my_list)
['alice', 'bob', 'chiara']

List Type and Methods

  • Lists has the type list
my_list = ["ali", "bob", "chiara"]
type(my_list)
list
  • There are specific operations that can be performed on lists.
  • You can add items to a list using the append() function.
my_list.append("dominique")

print(my_list)
['ali', 'bob', 'chiara', 'dominique']

Removing Items from a List in Python

  • You can remove items from a list using the pop() function.
  • The pop() function removes the last item in the list.
my_list = ["ali", "bob", "chiara"]

my_list.pop()
print(my_list)
['ali', 'bob']
  • The pop(index) function removes the item at the specified index.
my_list = ["ali", "bob", "chiara"]

my_list.pop(1)
print(my_list)
['ali', 'chiara']

Removing items based on value

  • You can remove items from a list using the remove() function.
  • The remove() function removes the first item with the specified value.
  • Example:
my_list = ["ali", "bob", "chiara", "bob"]

my_list.remove("bob")
print(my_list)
['ali', 'chiara', 'bob']

Combining two lists

  • You can combine two lists with + operator.
  • Example:
my_list1 = ["ali", "bob", "chiara"]
my_list2 = ["zoe", "yoshua"]

new_list = my_list1 + my_list2
print(new_list)
['ali', 'bob', 'chiara', 'zoe', 'yoshua']

Check if an Item Exists in a List in Python

  • You can check if an item exists in a list using the in operator.
  • Example:
my_list = ["ali", "bob", "chiara"]

"ali" in my_list
True
my_list = ["ali", "bob", "chiara"]

"alessandro" in my_list
False

Practice time

03_lists.ipynb

Logical Operators

  • We have two logical values: True and False

  • and and or and not are the logical operators

  • and means that both conditions must be true

  • or means that at least one condition must be true

  • not reverses the logical value

a = 5
b = 10
print(a == 5 and b == 10)
True
print(a == 5 and b == 5)
False
print(a == 1 or b == 10)
True
print(not a == 1)
True

Logical Operators

a = 5
b = 10
print(a == 1 or b == 10)
True
print(not a == 1)
True

if statement

my_variable = 42

if my_variable < 50:
    print("the variable is smaller than 50")
the variable is smaller than 50

Very important: Indentation

my_variable = 42

if my_variable < 50:
    print("the variable is smaller than 50")
  • Python doesn’t have braces like { } or end statements to indicate the span. Instead the hierarchy/ownership of the statements are determined by indents.
  • Four spaces is the accepted convention but you can use tab or the another number of spaces as long as it is consistent.
  • Graphical user interfaces often add four spaces instead of a tab.

else statement

my_variable = 42

if my_variable < 50:
    print("the variable is smaller than 50")
else:
    print("the variable is bigger than 50")
the variable is smaller than 50

elif statement

my_variable = 42

if my_variable < 40:
    print("the variable is smaller than 40")
elif my_variable < 50:
    print("the variable is between 40 and 50")
else:
    print("the variable is bigger than 50")
the variable is between 40 and 50

For loop over list items

  • Lists are not just good for collecting items. also for looping over them (Remember Ex2 last question)
my_list = [1,2,3,4]
for x in my_list:
  print(x ** 2)
1
4
9
16

Loop over a range of numbers

  • Python creates a range object that is iterable with range() function.

  • Then one can loop over it to make calculations.

for i in range(3,6):
  print(i**2)
9
16
25

Creating a new list using for loop

  • We can generate an empty list and add items recursively.
  • list_name.append() to add an item to a list

Example:

my_list = [1,2,3,4]

squares = []

for x in my_list:
  squares.append(x ** 2)
print(squares)
[1, 4, 9, 16]

List Comprehension

  • List comprehension is a shorter syntax when you create a new list based on another list.
my_list = [1,2,3,4]
squares = []

for x in my_list:
  squares.append(x ** 2)

we can write instead:

squares = [x ** 2 for x in my_list]
print(squares)
[1, 4, 9, 16]


\[ \text{Squares} = \{ x^2 | \text{ for all } x \in \text{my_list} \} \]

List Comprehension

my_list = [1,2,3,4]
squares = [x ** 2 for x in my_list]
print(squares)
[1, 4, 9, 16]



  • We can also add conditions
my_list = [1,2,3,4]
squares = [x ** 2 for x in my_list if x > 2]
print(squares)
[9, 16]

\[ \text{Squares} = \{ x^2 | \text{ for all } x \in \text{my_list}, x > 2 \} \]

Enumerate function

  • Enumerate function returns a tuple with index and the item.
others_choices = ["15","30","45"]

for i, x in enumerate(others_choices):
  print("Participant with index", i,  "chose", x, "tokens")
Participant with index 0 chose 15 tokens
Participant with index 1 chose 30 tokens
Participant with index 2 chose 45 tokens

Practice time

Continue on 03_lists.ipynb

Dictionaries

  • Also a collection of objects like lists
  • Unlike lists, items have keys (in other words keywords)
  • Can be created with:
    • {key1: value1, key2: value2}, or
    • dict(key1=value1, key2=value2)
my_dictionary = {'ali': 1987, 'bob': 1953, 'chiara':1980}
print(my_dictionary)
{'ali': 1987, 'bob': 1953, 'chiara': 1980}
my_dictionary2 = dict(ali=1987, bob=1953, chiara=1980)

print(my_dictionary2)
{'ali': 1987, 'bob': 1953, 'chiara': 1980}

Retrieving an item from dictionary

  • You can retreive an item from a dictionary by its key.
birthyears = {"ali": 1987, "bob": 1953, "chiara":1980}
birthyears["bob"]
1953

Adding a new item to dictionary

birthyears = {"ali": 1987, "bob": 1953, "chiara":1980}

birthyears['dana'] = 1992
print(birthyears)
{'ali': 1987, 'bob': 1953, 'chiara': 1980, 'dana': 1992}

Dictionaries are good for storing and looping matched data

people = [{"name": "ali", "year": 1987, "city": "Istanbul"},
          {"name": "bob", "year": 1953, "city": "London"},
          {"name": "chiara", "year": 1980, "city": "Rome"}]

for person in people:
    print("My name is " + person["name"] + ". I live in " + person["city"])
My name is ali. I live in Istanbul
My name is bob. I live in London
My name is chiara. I live in Rome

Practice time

04_dictionaries.ipynb

Functions in Python

  • Python has many built-in functions
ages = [39,48,21,59]

max(ages)
59
my_name = "ali"
len(my_name)
3

Some common functions

  • print() prints the value of the argument to the screen
  • abs() returns the absolute value of the argument
  • len() returns the length of the argument
  • type() returns the type of the argument
  • max() returns the maximum value of the argument
  • min() returns the minimum value of the argument
  • round() rounds the argument to the nearest integer
  • sum() returns the sum of all elements in the argument
  • sorted() returns a sorted version of the argument

We can build our own functions

  • Functions are defined with def keyword.
def max_min_difference(x):
    difference = max(x) - min(x)
    return(difference)
    


heights = [173, 153, 171, 190, 179] # in cm
max_min_difference(heights)
37

You will see functions in different forms

  • Indepedent functions
heights = [173, 153, 171, 190, 179]

min(heights)
153
  • Associated to objects (Methods)
heights.sort()
print(heights)
[153, 171, 173, 179, 190]
  • Associated to other objects than what it is applied to (Static methods)
helpers.shuffle(heights)
print(heights)

Functions may give output or not

  • Functions that give output are called fruitful functions
print(min(heights))
153
  • Functions that do not give output are called void functions
print(heights.append(180))
None

Functions may modify the objects they are applied to

  • Functions that modify the objects they are applied to are called modifiers
heights = [173, 153, 171, 190, 179]
heights.sort()
print(heights)
[153, 171, 173, 179, 190]
  • Functions that do not modify the objects they are applied to are called pure
heights = [173, 153, 171, 190, 179]
print(sorted(heights))
print(heights)
[153, 171, 173, 179, 190]
[173, 153, 171, 190, 179]

Practice time

05_functions.ipynb