Link Search Menu Expand Document

Module 05. Collections and Iteration

Lecture Date 1: September 20, 2021 - Monday Slides-1
Lecture Date 2: September 22, 2021 - Wednesday Slides-2
DataCamp DataCamp Chapters: Introduction to Python -> Python Lists
Intermediate Python -> Dictionaries and Pandas
Intermediate Python -> Loops

So far, we have learned about variables that can hold a value. In this lecture, we will learn special variable types (or objects to be correct) that can hold multiple values. Imagine, you would like to model the motion of masses and want to store all the trajectory points, it will be very difficult if you don’t use a collection like list which is the first part of this lecture. Simultaneously, if you want to work on lists, it is challenging to do so without using a concept called iteration, or loops. Loops allow the programmer to iterate through collections like lists. Loops will be the second topic of this lecture. Apart from lists, we will study three other collections types, namely tuples, dictionaries, and sets. We will cover when to use which collection with code examples. Once you master in lists and loops, you can build think about building cool models such as the one presented in the following video.

Table of contents:

1. Lists

Download code

1.1. Creating lists

cities = ["Fairfax", "Alexandria", "Reston", "Herndon", "Vienna", "Oakton", "Centreville"]
mixed_list = [1, "Banana", True, 1.0 ]
list_within_list = [1, 5, 10, ["one", "two", "three"], 25 ]

1.2. Accesing list elements

cities[0]
'Fairfax'
cities[4]
'Vienna'
cities[7]
---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

<ipython-input-6-ca6e618667fa> in <module>
----> 1 cities[7]


IndexError: list index out of range
print(cities[-1], cities[-4])
Centreville Herndon
print(cities[-8])
---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

<ipython-input-8-da8bc98ca84a> in <module>
----> 1 print(cities[-8])


IndexError: list index out of range
cities[1:4]
['Alexandria', 'Reston', 'Herndon']
list_within_list[3][0]
'one'

1.3. List Functions

new_list=[]
new_list.append(3.14)
new_list
[3.14]
new_list.append(-999.14)
new_list
[3.14, -999.14]
new_list.append(True)
new_list
[3.14, -999.14, True]
new_list.extend([5,6,7,5])
new_list
[3.14, -999.14, True, 5, 6, 7, 5]
new_list.insert(0, "Hello")
new_list
['Hello', 3.14, -999.14, True, 5, 6, 7, 5]
new_list.insert(4, "World")
new_list
['Hello', 3.14, -999.14, True, 'World', 5, 6, 7, 5]
new_list.insert(-1, ["inner","list"])
new_list
['Hello', 3.14, -999.14, True, 'World', 5, 6, 7, ['inner', 'list'], 5]
print(new_list.index(3.14))
1
print(new_list.pop())
5
new_list
['Hello', 3.14, -999.14, True, 'World', 5, 6, 7, ['inner', 'list']]
new_list.remove(["inner","list"])
new_list
['Hello', 3.14, -999.14, True, 'World', 5, 6, 7]
new_list.sort()
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-31-fa91de0f3b3b> in <module>
----> 1 new_list.sort()


TypeError: '<' not supported between instances of 'float' and 'str'
print(new_list.count(5))
1

1.4. Collection functions

cities = ["Fairfax", "Alexandria", "Reston", "Herndon", "Vienna", "Oakton", "Centreville"]
number_of_cities = len(cities)
print(number_of_cities)
7
print("Vienna" in cities)
print("Arlington" in cities)
True
False


2. Tuples, Dictionaries, and Sets

Download code

2.1. Tuples

cities_tuple = ("Fairfax", "Alexandria", "Reston", "Herndon", "Vienna", "Oakton", "Centreville")
print(cities_tuple)
('Fairfax', 'Alexandria', 'Reston', 'Herndon', 'Vienna', 'Oakton', 'Centreville')
cities_tuple2 = "Fairfax", "Alexandria", "Reston", "Herndon", "Vienna", "Oakton", "Centreville"
print(cities_tuple2)
('Fairfax', 'Alexandria', 'Reston', 'Herndon', 'Vienna', 'Oakton', 'Centreville')

Tuple packing

val1, val2, val3 = 100, 200, 300
print(val1, val2, val3)
100 200 300
val2, val1 = val1, val2
print(val1, val2, val3)
200 100 300

2.2. Sets

cities_set = {"Fairfax", "Alexandria", "Reston", "Herndon", "Vienna", "Oakton", "Centreville"}
print(cities_set)
{'Fairfax', 'Vienna', 'Oakton', 'Centreville', 'Alexandria', 'Herndon', 'Reston'}
cities_set2 = set(["Fairfax", "Alexandria", "Reston", "Herndon", "Vienna", "Oakton", "Centreville"])
print(cities_set2)
{'Fairfax', 'Vienna', 'Oakton', 'Centreville', 'Alexandria', 'Herndon', 'Reston'}
set2 = set([1,4,5,1,1,5,7,1,7,1,6,4,5,7,1])
print(set2)
{1, 4, 5, 6, 7}
set1 = set([1,2,3])
set2 = set([2,3,4])
print(set1.union(set2))
{1, 2, 3, 4}

2.3. Dictionary

dct = { }

dct[0] = 'some data'

dct[5] = [5, 'more data']

dct['astring'] = (4,5)

dct[(5,6)] = 'a point'

list(dct.keys())
[0, 5, 'astring', (5, 6)]
list(dct.values())
['some data', [5, 'more data'], (4, 5), 'a point']
# print keys before popping
print(list(dct.keys()))

# next line will remove the dictionary item w/ key=5
value = dct.pop(5)
print(f'Removed item value: {value}')

# print keys after popping
print(list(dct.keys()))
[0, 5, 'astring', (5, 6)]
Removed item value: [5, 'more data']
[0, 'astring', (5, 6)]

2.4. Collection functions

cities = ["Fairfax", "Alexandria", "Reston", "Herndon", "Vienna", "Oakton", "Centreville"]
number_of_cities = len(cities)
print(number_of_cities)
7
print("Vienna" in cities)
print("Arlington" in cities)
True
False

3. Loops

Download code
Imagine that you are asked to simulate the projection of a free falling object every 0.1 seconds.

y1=50 # initial position
vy=0 # initial velocity
g=9.8 # gravity

t=0.0
new_position = y1+vy*t-0.5*g*t**2
print(f"At time={t}, the position of the object is at {new_position}")

t=0.1
new_position = y1+vy*t-0.5*g*t**2
print(f"At time={t}, the position of the object is at {new_position}")

t=0.2
new_position = y1+vy*t-0.5*g*t**2
print(f"At time={t}, the position of the object is at {new_position}")

t=0.3
new_position = y1+vy*t-0.5*g*t**2
print(f"At time={t}, the position of the object is at {new_position}")

At time=0.0, the position of the object is at 50.0
At time=0.1, the position of the object is at 49.951
At time=0.2, the position of the object is at 49.804
At time=0.3, the position of the object is at 49.559

3.1. The for loop

cities = ["Fairfax", "Alexandria", "Reston", "Herndon", "Vienna", "Oakton", "Centreville"]
for city in cities:
    print(city)
Fairfax
Alexandria
Reston
Herndon
Vienna
Oakton
Centreville
for letter in "GMU":
    print(letter)
G
M
U
coordinates = [(0,0), (0.4, 0.1), (0.7, 0.2), (0.99, 0.3)]
for coor in coordinates:
    print("x,y: ",coor)
x,y:  (0, 0)
x,y:  (0.4, 0.1)
x,y:  (0.7, 0.2)
x,y:  (0.99, 0.3)
cities = ["Fairfax", "Alexandria", "Reston", "Herndon", "Vienna", "Oakton", "Centreville"]
for city in cities:
    for letter in city:
        print(letter,end=".")
    print()
F.a.i.r.f.a.x.
A.l.e.x.a.n.d.r.i.a.
R.e.s.t.o.n.
H.e.r.n.d.o.n.
V.i.e.n.n.a.
O.a.k.t.o.n.
C.e.n.t.r.e.v.i.l.l.e.

3.2. Range

for num in range(9, 0, -2):
    print(num)
9
7
5
3
1
for num in range(5):
    print(num*num)
0
1
4
9
16

3.3. Enumerate

cities = ["Fairfax", "Alexandria", "Reston", "Herndon", "Vienna", "Oakton", "Centreville"]
for index in range(len(cities)):
    print(index+1,".",cities[index])
1 . Fairfax
2 . Alexandria
3 . Reston
4 . Herndon
5 . Vienna
6 . Oakton
7 . Centreville
for index, city in enumerate(cities):
    print(index+1,".",city)
1 . Fairfax
2 . Alexandria
3 . Reston
4 . Herndon
5 . Vienna
6 . Oakton
7 . Centreville

3.4. Zip

indexes = [1, 2, 3, 4, 5, 6, 7]
cities = ["Fairfax", "Alexandria", "Reston", "Herndon", "Vienna", "Oakton", "Centreville"]
for item in zip(indexes, cities):
    print(item)
(1, 'Fairfax')
(2, 'Alexandria')
(3, 'Reston')
(4, 'Herndon')
(5, 'Vienna')
(6, 'Oakton')
(7, 'Centreville')
for item in zip(indexes, cities):
    print(item[0],".",item[1])
1 . Fairfax
2 . Alexandria
3 . Reston
4 . Herndon
5 . Vienna
6 . Oakton
7 . Centreville
list1 = [0,1,2]
list2 = ["zero", "one", "two"]
list3 = ["cero", "uno", "dos"]
for item in zip(list1, list2, list3):
    print(item)
(0, 'zero', 'cero')
(1, 'one', 'uno')
(2, 'two', 'dos')
list1 = [0,1,2]
list2 = ["zero", "one", "two", "three"]
for item in zip(list1, list2):
    print(item)
(0, 'zero')
(1, 'one')
(2, 'two')
list1 = [0,1,2, 3]
list2 = ["zero", "one", "two"]
for item in zip(list1, list2):
    print(item)
(0, 'zero')
(1, 'one')
(2, 'two')

3.5. The while loop

index = 0
while index < 5:
    index = index + 1 # or index+= 1
    print(index)
1
2
3
4
5
list2 = ["zero", "one", "two"]
index = 0
while index < len(list2):
    print(list2[index])
    index+= 1
zero
one
two

3.6 Control Flow

for num in range(11):
    if num % 2 == 0:
        print(num, "is an even number.")
    else:
        print(num, "is an odd number.")
0 is an even number.
1 is an odd number.
2 is an even number.
3 is an odd number.
4 is an even number.
5 is an odd number.
6 is an even number.
7 is an odd number.
8 is an even number.
9 is an odd number.
10 is an even number.
num = 0
max_number = 5
while True:
    if num > max_number:
        break
        
    if num % 2 == 0:
        print(num, "is an even number.")
    else:
        print(num, "is an odd number.")
        
    num += 1
0 is an even number.
1 is an odd number.
2 is an even number.
3 is an odd number.
4 is an even number.
5 is an odd number.
for num in range(11):
    if num % 2 == 0:
        continue
    print(num, "is an odd number.")
1 is an odd number.
3 is an odd number.
5 is an odd number.
7 is an odd number.
9 is an odd number.
first_list = ["Hello", "World", 2000, True]
empyt_tuple = tuple()
one_elem_list = list([True])
print( any(first_list))
print( all(first_list))
print( any(empyt_tuple))
print( all(empyt_tuple))
print( any(one_elem_list))
print( all(one_elem_list))
True
True
False
True
True
True

3.7. Example

Three ways of generating numbers from 0.0 to 3.0 with .1 increments

time = []
for i in range(31):
    time.append(i/10.0)
print (time)
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3.0]
time = []
i = 0
while i <= 30:
    time.append(i/10)
    i += 1
print (time)
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3.0]
time = [i/10 for i in range(31)]
print(time)
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3.0]

3.8. Print example (see slides)

num_of_character = 10
charachter_to_print = "*"

for i in range(num_of_character):
    print(end=charachter_to_print)
**********
num_of_character = 20
charachter_to_print = "-"

counter=0
while counter < num_of_character:
    print(end=charachter_to_print)
    counter = counter + 1
--------------------

3.9. Dropping example (see slides)

starting_height = 100
initial_velocity = 0
gravity = -9.8
pos_list = [starting_height]
for i in range(1,46):
    t = i / 10
    y2 = starting_height + initial_velocity*t + 0.5 * gravity * t ** 2
    pos_list.append(y2)
    #print(“time:“,t, ” height:“, y2)

print("-----------")
print("Positions")
print(pos_list)
distance_list = []

for i in range(len(pos_list)-1):
    distance_list.append(pos_list[i]-pos_list[i+1])
print("-----------")
print("Distances")
print (distance_list)
-----------
Positions
[100, 99.951, 99.804, 99.559, 99.216, 98.775, 98.236, 97.599, 96.864, 96.031, 95.1, 94.071, 92.944, 91.719, 90.396, 88.975, 87.45599999999999, 85.839, 84.124, 82.311, 80.4, 78.39099999999999, 76.28399999999999, 74.07900000000001, 71.776, 69.375, 66.876, 64.279, 61.584, 58.791, 55.9, 52.91099999999999, 49.823999999999984, 46.639, 43.356, 39.974999999999994, 36.49599999999999, 32.91899999999998, 29.244, 25.471000000000004, 21.599999999999994, 17.631, 13.563999999999993, 9.399000000000001, 5.1359999999999815, 0.7749999999999915]
-----------
Distances
[0.049000000000006594, 0.14699999999999136, 0.24500000000000455, 0.3430000000000035, 0.4409999999999883, 0.5390000000000015, 0.6370000000000005, 0.7349999999999994, 0.8329999999999984, 0.9310000000000116, 1.0289999999999964, 1.1269999999999953, 1.2250000000000085, 1.3229999999999933, 1.4210000000000065, 1.5190000000000055, 1.6169999999999902, 1.7150000000000034, 1.8129999999999882, 1.9110000000000014, 2.0090000000000146, 2.1069999999999993, 2.204999999999984, 2.3030000000000115, 2.4009999999999962, 2.4989999999999952, 2.5970000000000084, 2.694999999999993, 2.7930000000000064, 2.8909999999999982, 2.9890000000000114, 3.0870000000000033, 3.184999999999981, 3.2830000000000013, 3.3810000000000073, 3.4790000000000063, 3.5770000000000053, 3.674999999999983, 3.772999999999996, 3.8710000000000093, 3.968999999999994, 4.067000000000007, 4.164999999999992, 4.263000000000019, 4.36099999999999]


Back to top

Copyright © Hamdi Kavak. CDS 230 - Modeling and Simulation 1.