banana
orange
apple
PHOT 110: Introduction to programming
LECTURE 04
Michaël Barbier, Spring semester (2023-2024)
while
loop:
Iterate over a sequence: list
, range
, etc.
But … We can actually iterate over other types: string
, set
, etc.
list
, range
, strings (str
)len()
, .sort()
a_string = "Pretzel"
a_list = [3, 105, 56]
a_range = range(4)
print(f"The ID of a_string: {a_string} = { id(a_string) }")
print(f"The ID of a_list: {a_list} = { id(a_list) }")
print(f"The ID of a_range: {a_range} = { id(a_range) }")
The ID of a_string: Pretzel = 2135801745536
The ID of a_list: [3, 105, 56] = 2135519091008
The ID of a_range: range(0, 4) = 2135801181456
str
) are immutableA = "Pretzel"
B = A.upper()
print(f"String A: {A} is still the same as A: {A}")
print(f"String B: {B} is the uppercase version of A: {A}")
print(f"ID of B: {id(B)} is not equal to ID of A: {id(A)}")
String A: Pretzel is still the same as A: Pretzel
String B: PRETZEL is the uppercase version of A: Pretzel
ID of B: 2135801527968 is not equal to ID of A: 2135801745536
Syntax to define a tuple:
Cast another collection to tuple, e.g. from list
:
Lists are mutable
Lists are mutable
Type | mutable | item type |
---|---|---|
list |
yes | mixed types |
tuple |
no | mixed types |
range |
no | integers |
str |
no | characters |
Sequence operations are available according to mutability and type
<bool> = el in s # --> True/False
<bool> = el not in s # --> True/False
s = s1 + s2 # concatenate s1 and s2
s * n or n * s # n times concatenation
Examples
Note: concatenation does not work for ranges
el = s[i] # Select element i
s = s[start:end+1:step] # Slicing
n = s.count[<el>] # Count elements
i = s.index[<el>] # index first el
For a tuple:
s = ("Malta", "Corsica", "Lesvos", "Malta"); print(s)
print(f"Third element of s: { s[2] }")
print(f"Slice of s: { s[1:] }")
print(f"'Malta' appears: { s.count('Malta') } times")
print(f"First index of 'Malta': { s.index('Malta') }")
('Malta', 'Corsica', 'Lesvos', 'Malta')
Third element of s: Lesvos
Slice of s: ('Corsica', 'Lesvos', 'Malta')
'Malta' appears: 2 times
First index of 'Malta': 0
el = s[i] # Select element i
s = s[start:end+1:step] # Slicing
n = s.count[<el>] # Count elements
i = s.index[<el>] # index first el
For a list:
s = ["Malta", "Corsica", "Lesvos", "Malta"]; print(s)
print(f"Third element of s: { s[2] }")
print(f"Slice of s: { s[1:] }")
print(f"'Malta' appears: { s.count('Malta') } times")
print(f"First index of 'Malta': { s.index('Malta') }")
['Malta', 'Corsica', 'Lesvos', 'Malta']
Third element of s: Lesvos
Slice of s: ['Corsica', 'Lesvos', 'Malta']
'Malta' appears: 2 times
First index of 'Malta': 0
List is the only mutable sequence (so far)
<list>[i] = <el>
<list>.remove(<el>) # remove first <el>
<list>.insert(i, <el>) # insert <el> at index i
<el> = <list>.pop(i) # return <el> at i and remove
<list>.append(<el>) # Or: <list> += <el>
<list>.extend(<iterable>) # Or: <list> += <iterable>
<list>.sort() # Sorts list in-place
<list>.reverse() # Reverses list in-place
Examples:
fruits = ["banana", "orange", "pear", "peach"]
nuts = ("almond", "walnut")
fruits.remove("banana") # remove first <el>
fruits.insert(0, "mango") # insert <el> at index i
el = fruits.pop(3) # return <el> at i and remove
print(f"We popped {el}")
fruits.append("mandarin") # Or: <list> += <el>
fruits.extend(nuts) # Or: <list> += <iterable>
fruits.sort() # Sorts list in-place
fruits.reverse() # Reverses list in-place
print(fruits)
We popped peach
['walnut', 'pear', 'orange', 'mango', 'mandarin', 'almond']
Items of immutable types cannot change \(\Rightarrow\) return value
continue
skips a single iteration in while
or for
loop
The element with index: 0 = 22
The element with index: 1 = 20
The element with index: 2 = 34
The element with index: 4 = 25
The element with index: 5 = 78
break
stops the current while
or for
loop
The element with index: 0 = 22
The element with index: 1 = 20
The element with index: 2 = 34
pass
performs no action, purpose
High: 2, Low: 5
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
List comprehension
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
[0. 0.5 1. 1.5 2. 2.5 3. 3.5 4. 4.5 5. ]
[2.5 3. 4. ] + [ 1. 0.1 10. ] = [ 3.5 3.1 14. ]
[2.5 3. 4. ] * [ 1. 0.1 10. ] = [ 2.5 0.3 40. ]
[2.5 3. 4. ] / [ 1. 0.1 10. ] = [ 2.5 30. 0.4]
We will see more complex plots later on. If you want to look ahead: https://matplotlib.org/stable/users/explain/quick_start.html
import matplotlib.pyplot as plt
import numpy as np
# Create the coordinate of a spiral
angles = np.linspace(0, 5*np.pi, 100)
radii = np.linspace(0, 4, 100)
xs = radii * np.cos(angles)
ys = radii * np.sin(angles)
# Plot spiral points with increasing size and color-value
plt.scatter(xs, ys, 10*radii, radii/4);
a
and b
) of same length:
while
loopfor
loop with range(len(a))
for
loop with enumerate(a)
for
loop with zip(a, b)
zip(a, b)
a
and b
\[
\begin{aligned}
x = a \cos(t)\\
y = b \cos(t)
\end{aligned}
\]len(a)
gives the length of the listlen(a)
gives the length of the listrange(len(a))
gives numbers from 0 to len(a) - 1
a
and b
are treated differentlyzip(a,b)
merges lists a and b as iterator of tuples (a[i],b[i])
zip(a,b)
merges lists a and b as iterator of tuples (a[i],b[i])
for
loop:enumerate()
?enumerate()
makes a “list” of tupleszip()
[(0, (1.0, 1.0)), (1, (1.25, 0.8)), (2, (1.5, 0.67)), (3, (1.75, 0.57)), (4, (2.0, 0.5))]
This looks cumbersome !
range()
and zip()
?[(0, 1.0, 1.0), (1, 1.25, 0.8), (2, 1.5, 0.67), (3, 1.75, 0.57), (4, 2.0, 0.5)]
# Method 5 using list comprehension with zip()
[plt.plot(ai*np.cos(t), bi*np.sin(t)) for ai, bi in zip(a, b)];
Lecture 05: for loops, sequences, enumerate, arrays