Lists and Loops
Advanced Control Flows
Review
- What are Boolean Values?
- What are Boolean operators and expressions?
- How do IF statements work?
Lists
A list is a more complex Python data type
It is an ordered sequence (or container) of values
marked by opening and closing brackets
demo_list = [2, "some string", True, 4, 5, None]
Lists can be nested (an item in a list can be a separate list)
nested_list = [5, 7, [99, "test"]]
List Indexing
Because lists are ordered,
we can search for items at particular locations.
This is called "Indexing"
colors = ["blue", "black", "red", "green"]
# The first element in a list is located at position 0blue = colors[0]
red = colors[2]
green = colors[-1]
# same applies to strings, which are also ordered sequencestest_string = "hello world"letter_h = test_string[0]
List Slicing
In addition to looking up items at particular indexes,
we can also retrieve multiple items at different position.
This is called "Slicing"
colors = ["black, "blue", "green", "orange"]first_three_colors = colors[0:3]alt_approach_for_first_three = color[:3]final_two_colors = colors[3:]
List operations
We can add, remove, alter, sort and perform several other operations on lists using built in functions
my_scores = [] # use the append() function to add an item to a list my_scores.append(89) my_scores.append(70) # use the remove function to remove() to eliminate an item my_scores.remove(89)
# Use indexing to alter an item my_scores[0] = 65
For loops
What if we want to perform an action on
all the elements in a sequence?
The answer is a for-loop
for some_variable_name in [33, "Bob", None, True]: print some_variable_name
For-loops run their body code for each item in a sequence.
In this case, the print statement is called 4 times
and each time, the item is assigned to some_variable_name
For loops Advanced
We can abruptly exit a for loop or alter it's flow
with break and continue statements respectively
for i in range(10): if i == 2: continue elif i == 5: break print i
While loops
Hybrid of Conditional Statements (IF/ELSE and LOOPS)
while [boolean expression ==True]:
# execute this loop body
# over and over again
While loops are not used very often.
Typically implemented when we want to loop
an undefined number of times