In [169]:
count = 0
while count < 100:
count += 1
count
Out[169]:
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)
For loops operate on elements in a list.
Basic structure:
for <element> in <list>:
<do something with element>
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
Out[172]:
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
Out[173]:
Note that you do not have to
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))
In [175]:
for massRatio in massRatioList:
print(massRatio)
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
In [177]:
index
Out[177]:
side-ways
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
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 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
Out[182]:
In [183]:
range?
In [184]:
print(list(range(-10, 2, 2)))
print(list(range(-5)))
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]:
For fun: using a function as an argument:
In [187]:
print(list(range(-10, 0, 2)))
len(range(-10, 0, 2))
Out[187]:
For our mass ratio list example:
In [189]:
massRatioList = []
for massRatio in range(1, 11, 1):
massRatioList.append(massRatio)
massRatioList
Out[189]:
Use range()
for the massRatioList itself!
In [191]:
massRatioList = list(range(1,11))
massRatioList
Out[191]:
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])
This is better:
In [193]:
for i, massRatio in enumerate(massRatioList): # enumerate returns both the index and the item
print(i, massRatio)
In [194]:
# Equivalently (but not exactly the same):
for stuff in enumerate(massRatioList):
print(stuff[0], stuff[1])
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]:
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]:
In [198]:
a[0] = 3
a
Out[198]:
In [203]:
a = tuple(a)
a
Out[203]:
In [204]:
print(t[0])
In [205]:
t[0] = 8
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=' ')
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
In [210]:
for index in range(0, numElements):
massRatio = massRatioMin + index * massRatioDelta
massRatios.append(massRatio)
print(index, massRatio)
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)
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))
In [213]:
a = range(1,11)
b = range(21,31 )
In [215]:
list(a)
Out[215]:
In [216]:
list(b)
Out[216]:
In [217]:
for itema, itemb in zip(a,b):
print(itema, itemb)
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))
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))
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))
In [221]:
mylist = []
for i in range(10):
mylist.append(i)
mylist
Out[221]:
can be written as:
In [224]:
mylist = [i**2 for i in range(10)]
mylist
Out[224]:
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))
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
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.
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 [ ]: