Some meta comments

  • My teaching feedback
    • References to the future are mostly just abstract without a mental map.
    • Same is true with references to other programming languages if you are not familiar with them.
    • Focus on one teaching object at a time.
  • Devices in class room
  • Why tutorials?

Recap: while loops and lists

What does it do?


In [169]:
count = 0
while count < 100:
    count += 1
count


Out[169]:
100

Q. What would this program print?

Rather than type in long lists, we can use while loops:


In [170]:
#
# Initializations first
#
massRatioList = []         # Creates an empty list
massRatioValue = 1   # For the conditional
massRatioMax = 15   # Also for the conditional
#
# And the while loop:
# 
while massRatioValue <= massRatioMax:  # Note the colon!
    massRatioList.append(massRatioValue)   # Note the indentation!
    massRatioValue += 1

In [171]:
print(massRatioList)
print(massRatioValue)


[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
16

Today: for loops and lists, list comprehensions, tuples

For loops operate on elements in a list.

Basic structure:

for <element> in <list>:
    <do something with element>

will be a variable name assigned to individual elements in

as opposed to while loops:

while <condition is True>:
    <do something>

In [172]:
for massRatio in massRatioList:  # Note the colon!
    print(massRatio) # Note the indent!

massRatio


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Out[172]:
15

In [173]:
for massRatio in massRatioList:  # Note the colon!
    print('massRatioList element = {}'.format(massRatio)) # Note the indent!

print('\nmassRatioList has {} elements!'.format(len(massRatioList)))
massRatio


massRatioList element = 1
massRatioList element = 2
massRatioList element = 3
massRatioList element = 4
massRatioList element = 5
massRatioList element = 6
massRatioList element = 7
massRatioList element = 8
massRatioList element = 9
massRatioList element = 10
massRatioList element = 11
massRatioList element = 12
massRatioList element = 13
massRatioList element = 14
massRatioList element = 15

massRatioList has 15 elements!
Out[173]:
15

Note that you do not have to

  • know the length of the list
  • define a walking index.

Let's use a for loop to make a table of mass ratios and gravitational forces:


In [174]:
# First, initialize variables
G       = 6.67e-11           # Grav. const.
mEarth  = 5.97e24            # Earth mass
mPerson = 70                 # Person mass 
radius  = 6.37e6             # Earth radius

massRatioList  = []          # Creates an empty list
massRatioValue = 1           # First mass ratio value
massRatioMax   = 15          # Last mass ratio value

# Create a list of mass ratios using a for loop
for massRatioValue in range(massRatioValue, massRatioMax + 1):   # Note the "+ 1"
    massRatioList.append(massRatioValue)

# Make a header for the table
print("# Mass-Ratio\tForce")

# Calculate the force for each mass ratio
for massRatio in massRatioList:
    force = G * massRatio * mEarth * mPerson / radius**2  

    # print contents of table line-by-line
    print("{}\t\t{:.2f}".format(massRatio, force))


# Mass-Ratio	Force
1		686.94
2		1373.88
3		2060.82
4		2747.76
5		3434.70
6		4121.65
7		4808.59
8		5495.53
9		6182.47
10		6869.41
11		7556.35
12		8243.29
13		8930.23
14		9617.17
15		10304.11

Note, how the force value automatically became a float, how it should be.

While loop implementation of a for loop

A simple for loop:


In [175]:
for massRatio in massRatioList:
    print(massRatio)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Can also be implemented as a while loop:


In [176]:
index = 0   # Remember that the index starts with zero!
while index < len(massRatioList):
    print(massRatioList[index])
    index += 1


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

This is a little less compact, but very intuitive.

Q. What is the value of index at the end (trace it!)?


In [177]:
index


Out[177]:
15

Interlude: make print work side-ways

Q. How could I learn about the ability's of print?

The built-in help system

IPython and therefore its kernel here in Jupyter has a built-in help system. It depends on code author to fill in these docstrings (I show you how later.)

Enter help system by calling object?. In Jupyter a sub-window appears. When done reading you leave it by pressing q or clickin the x in the upper right corner.

Example: Learn how to make print print side-ways.


In [178]:
print?

In [181]:
index = 0   # Remember that the index starts with zero!
while index < len(massRatioList):
    print(massRatioList[index], end=' ')
    index += 1


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 

The "range" function

An easy way to populate lists!

(In case you haven't noticed, there are already Python functions to do most things!)

Syntax: range(n) generates integers 0, 1, 2, ... n-1

Syntax: range (start, stop, step) generates from start to stop-1 with stepsize = step If step is not specified, it is assumed to be 1.

Python 3 to 2 difference:

Python 3 returns a generator for the list, not the list itself.

That means, if you want to see the list, it needs to be fully generated. To enforce this, convert the generator with the list funcion:


In [182]:
mygenerator = range(10)  # note how the print out also shows the default 0 starting value.
print(mygenerator)
mylist = list(mygenerator)
mylist


range(0, 10)
Out[182]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [183]:
range?

Q. What does this generate?


In [184]:
print(list(range(-10, 2, 2)))
print(list(range(-5)))


[-10, -8, -6, -4, -2, 0]
[]

Q. Why is the last list empty?

A. Because the default values don't match.

Calling range() with only 1 value means it is intepreted as STOP value, with START assumed to be 0 and STEP to be +1.

So,

range(-5)

is the same as

range(0,-5,1)

See why the list is empty?

Does this work?


In [185]:
list(range(0, -5))


Out[185]:
[]

No, because the last default value is -1! We wanted:


In [186]:
list(range(0, -5, -1))


Out[186]:
[0, -1, -2, -3, -4]

For fun: using a function as an argument:


In [187]:
print(list(range(-10, 0, 2)))
len(range(-10, 0, 2))


[-10, -8, -6, -4, -2]
Out[187]:
5

For our mass ratio list example:


In [189]:
massRatioList = []
for massRatio in range(1, 11, 1):
    massRatioList.append(massRatio)
massRatioList


Out[189]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Q. What could we simplify now, knowing about the range function?

Use range() for the massRatioList itself!


In [191]:
massRatioList = list(range(1,11))
massRatioList


Out[191]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The "enumerate" function

Often, you'll want the indices and the list element values, to steer or access other values in other lists. Python has a short-cut function for this sort of thing: enumerate

Note: This is better Python style than to create your index yourself and use that to access elements in the array. So, this is bad(-ish):


In [192]:
for i in range(len(massRatioList)):
    print(i, massRatioList[i])


0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10

This is better:


In [193]:
for i, massRatio in enumerate(massRatioList):  # enumerate returns both the index and the item
    print(i, massRatio)


0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10

In [194]:
# Equivalently (but not exactly the same):

for stuff in enumerate(massRatioList):
    print(stuff[0], stuff[1])


0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10

Python tries to be helpful here! As learned above, enumerate returns both the index and the current item for the loop.

It could have thrown you an error, because you only catch one value. Instead, in Python, it stores too many items in a new compound item:


In [195]:
# Notice the parentheses.
# What kind of variable type is stuff?

type(stuff)


Out[195]:
tuple

In [ ]:
print(stuff)

Tuples are the so called immutable versions of lists. Useful if you want to make sure you don't accidently change them while using them:


In [197]:
a = [1,2]
a


Out[197]:
[1, 2]

In [198]:
a[0] = 3
a


Out[198]:
[3, 2]

In [203]:
a = tuple(a)
a


Out[203]:
(3, 2)

In [204]:
print(t[0])


3

In [205]:
t[0] = 8


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-205-e765ed0031c3> in <module>()
----> 1 t[0] = 8

TypeError: 'tuple' object does not support item assignment

Processing lists simultaneously with for loops

The following construction is a bit lengthy (with 3 loops), but it shows how multiple lists (massRatioList and forceList) can be processed simultaneously with for loops

Good mnemonic for lists: Use PLURAL!


In [206]:
massRatios = range(5)

In [207]:
for massRatio in massRatios:
    print(massRatio, end=' ')


0 1 2 3 4 

In [209]:
massRatios  = []        # Initialize.Why? If it's not there, can't append!
numElements    = 10        # Number of elements
massRatioMin   = 1      # Minimum mass ratio
massRatioMax   = 10      # Maximum mass ratio
massRatioDelta = (massRatioMax - massRatioMin) / (numElements - 1)   # Mass ratio increment
Now, construct massRatios:

In [210]:
for index in range(0, numElements):
    massRatio = massRatioMin + index * massRatioDelta
    massRatios.append(massRatio)
    print(index, massRatio)


0 1.0
1 2.0
2 3.0
3 4.0
4 5.0
5 6.0
6 7.0
7 8.0
8 9.0
9 10.0

Now, calculate the forces using massRatios:


In [211]:
G         = 6.67e-11         # Gravitational constant
mEarth    = 5.97e24          # Earth mass
mPerson   = 70               # Person mass 
radius    = 6.37e6           # Earth radius
forces = []               # Empty list -- I don't have to specify its length

for massRatio in massRatios:
    force = massRatio * G * mEarth * mPerson / radius**2  
    forces.append(force)
Finally, to print the table: (demonstrating processing lists simultaneously)

In [212]:
print("Index\tM_Ratio\tForce")  # note how special characters are tightly embedded into the string

#for index in range(min(len(massRatioList), len(forceList))):
for index in range(len(massRatios)):
    massRatio = massRatios[index]
    force = forces[index]
    print('{}\t{:.1f}\t{:.2f}'.format(index, massRatio, force))


Index	M_Ratio	Force
0	1.0	686.94
1	2.0	1373.88
2	3.0	2060.82
3	4.0	2747.76
4	5.0	3434.70
5	6.0	4121.65
6	7.0	4808.59
7	8.0	5495.53
8	9.0	6182.47
9	10.0	6869.41

In [213]:
a = range(1,11)
b = range(21,31 )

In [215]:
list(a)


Out[215]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [216]:
list(b)


Out[216]:
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]

In [217]:
for itema, itemb in zip(a,b):
    print(itema, itemb)


1 21
2 22
3 23
4 24
5 25
6 26
7 27
8 28
9 29
10 30

Above the index is not used for calculations, therefore there is a better way to do it: Use zip to combine lists in a 'zipper' like fashion.

The automatic unpacking of tuples can never have too many receivers, but it can too few!


In [218]:
print("Index\tm_Ratio\tForce")  # note how special characters are tightly embedded into the string

#for index in range(min(len(massRatioList), len(forceList))):
for i, massRatio, force in enumerate(zip(massRatios, forces)):
    print('{}\t{:.1f}\t{:.2f}'.format(i, massRatio, force))


Index	m_Ratio	Force
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-218-391321ba32b8> in <module>()
      2 
      3 #for index in range(min(len(massRatioList), len(forceList))):
----> 4 for i, massRatio, force in enumerate(zip(massRatios, forces)):
      5     print('{}\t{:.1f}\t{:.2f}'.format(i, massRatio, force))

ValueError: not enough values to unpack (expected 3, got 2)

In [219]:
print("Index\tm_Ratio\tForce")  # note how special characters are tightly embedded into the string

#for index in range(min(len(massRatioList), len(forceList))):
for i in enumerate(zip(massRatios, forces)):
    print('{}\t{:.1f}\t{:.2f}'.format(i, massRatio, force))


Index	m_Ratio	Force
(0, (1.0, 686.9408456535615))	10.0	6869.41
(1, (2.0, 1373.881691307123))	10.0	6869.41
(2, (3.0, 2060.822536960685))	10.0	6869.41
(3, (4.0, 2747.763382614246))	10.0	6869.41
(4, (5.0, 3434.7042282678076))	10.0	6869.41
(5, (6.0, 4121.64507392137))	10.0	6869.41
(6, (7.0, 4808.585919574931))	10.0	6869.41
(7, (8.0, 5495.526765228492))	10.0	6869.41
(8, (9.0, 6182.467610882054))	10.0	6869.41
(9, (10.0, 6869.408456535615))	10.0	6869.41

In [220]:
print("Index\tm_Ratio\tForce")  # note how special characters are tightly embedded into the string

#for index in range(min(len(massRatioList), len(forceList))):
for i, (massRatio, force) in enumerate(zip(massRatios, forces)):
    print('{}\t{:.1f}\t{:.2f}'.format(i, massRatio, force))


Index	m_Ratio	Force
0	1.0	686.94
1	2.0	1373.88
2	3.0	2060.82
3	4.0	2747.76
4	5.0	3434.70
5	6.0	4121.65
6	7.0	4808.59
7	8.0	5495.53
8	9.0	6182.47
9	10.0	6869.41

List comprehension

Really, really compact way of populating lists:

In [221]:
mylist = []
for i in range(10):
    mylist.append(i)
mylist


Out[221]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

can be written as:


In [224]:
mylist = [i**2 for i in range(10)]
mylist


Out[224]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

In [226]:
numElements = 10

massRatios = [1.0 + index for index in range(numElements)]          # list comprehension!
forces     = [massRatio * G * mEarth * mPerson / radius**2\
              for massRatio in massRatios]

Wow, that is compact! Two lines! Did it work?


In [227]:
print("Mass Ratio\tForce")  # note that "Mass Ratio" is so long, it swallows one \t from below.

for massRatio,force in zip(massRatios, forces):
    print('{:.1f}\t\t{:.2f}'.format(massRatio, force))


Mass Ratio	Force
1.0		686.94
2.0		1373.88
3.0		2060.82
4.0		2747.76
5.0		3434.70
6.0		4121.65
7.0		4808.59
8.0		5495.53
9.0		6182.47
10.0		6869.41

Learn how fast your code works


In [229]:
%%timeit  # this is called "IPython magic"
massRatios = [0] * numElements
forces     = [0] * numElements

#  Using a single for loop, populate the two lists
for index in range(len(massRatios)):
    #  Calculate the mass ratio
    massRatios[index] = massRatioMin + index * massRatioDelta

    #  Calculate the force
    forces[index] = massRatioList[index] * G * mEarth * mPerson / radius**2


100000 loops, best of 3: 6.95 µs per loop

In [228]:
%%timeit?

In [ ]:
%%timeit
numElements = 10

massRatios = [1.0 + index for index in range(numElements)]          # list comprehension!
forces     = [massRatio * G * mEarth * mPerson / radius**2 for massRatio in massRatioList]

In Python 2 the shorter version was 26% faster, in Python 3 not much.

While writing compact code is elegant, it may come at the cost of readability.

Use with caution!

Advice: err on the side of easily comprehensible code.

Q. When might you use a while loop instead of a for loop?

Q. When might you use a for loop instead of a while loop?

If you don't have a tidy data structure to iterate through, or you don't have a generator function (like range()) that drives your processing, you must use while.


In [ ]: