python iterations
run, check conditions, loop back, repeat
Quick Intro & Terminology
Loops allow programmers to repeat steps multiple times until some condition is met or the condition has reached the pre-specified number of iterations
Iterable - an object capable of returning its members one at a time, i.e. it is anything that has a collection of things (e.g., list, tuple, range, dictionary, map, zip)
Iterator - a class in Python that gives us access to two special methods: __iter__ and __next__
iter allows object to remember where it is during iteration
next tells object how to get the next value
an iterator can be an iterable
Iterable vs. Iterator
think of iterable as an adjective, an object that is “capable of”
think of iterator as a verb, actually iterating objects by calling the next() function
Iter() is a function used on an iterable to return an iterator object
Next() is a function used on an iterator will return elements one by one and “consume” them each time the function is run; when end is reached, an error will show unless you set a default value
During a For Loop, the iterable (list) is converted to an iterator in the backend which gives it the __iter__ and __next__methods; each element is pulled and stored into the variable until the list is exhausted
iterable vs. iterator
Iterables can also be used in other functions:
Map is a function that applies a given function to each item of an iterable (e.g., list) and returns an iterator (e.g., map object)
syntax is map(function, object)
use a non-mutating operator so that there is a return
you can pass through multiple arguments
use a lambda function if you want to use operators like + or -
Zip is a binary function that takes two lists of the same length and makes one list containing pairs of corresponding elements of the two lists
useful in combing multiple iterables into one iterable
elements in the zipped lists are tuples
Filter is similar to map, but filter goes through each element in the iterable and returns certain values based on the condition
syntax is filter(function, iterable)
function acts as a condition checking if the sequence is True or False
returns a filtered iterator
Enumerate is a function that returns the index and the element from the iterable in the form of a tuple pair
the function returns an enumerate object, an iterator
default starting index is zero; if you want to override this, enter the starting point as the second argument in the function
you can use this function within a for loop; the results will print each index with its element
Reduce is a function from the functools module that applies a function to an iterable and reduces it to a single cumulative value
syntax is functools.reduce(function, iterable)
cumulatively adds two elements of the list from left to right
Yield can be used instead of return within a function and the function will have an iterator property. Technically, this will return a generator object which is a special case of iterator. A generator is an iterator but not vice versa. (Example on right)
Compared to all these iterable functions with clear purposes, the for loop statement acts as a jack of all trades but obscures the actual operation that the loop performs
Rule of thumb: use non-mutating operation for map() to get a return, use for loop for mutating operations
Example: an instance when the iterator is an iterable
the original iterable is a nested list
when this nested list was filtered for empty lists (defined by function ‘not_empty’), it became an iterator during the code: filter(not_empty, nested_list)
but at the same time, it was an iterable for the function ‘first_item’ which pulled the first element at [0] index during the code: map(first_item, iterator)
For Loop / While Loop
For Loop - a programming structure that allows you to achieve iteration, the process of repeatedly performing a set of instructions; typically used to iterate over a sequence of data
syntax is for i in <sequence>: <next line with indent> <statement>
you can read it as: for each element in this sequence, do this statement until you reach the end.
in each iteration, the element is stored into the variable i, which means the variable changes at each iteration
the variable can be called anything and does not need to be assigned outside of the loop
in the back-end, the for loop is converting the iterable to iterator and performing the next() function
a for loop can be within another for loop, also known as Nested Loop
cannot use the map() function in a for loop with print() because print() does not hold any value
While Loop - repeats a task until the condition is evaluated as False; unlike For Loop, the While Loop needs the loop variable to be created and initialized beforehand; to initialize a variable means to give the variable an initial value
syntax is while <Boolean condition>: <next line with indent><statement>
you can read it as: while the condition is True, execute the statement until it is False.
unlike for loops, a sequence to iterate over is not required
while loop does not increment values like a for loop can
beware of infinite loop which is a loop that never reaches its stopping condition
After each iteration, the loop checks the condition; if the condition tells the loop whether to stop or continue, so the condition within the loop is crucial as it determines how long the loop will run for
These are additional statements that allow us to have more control of loop statements:
Break - this statement immediately terminates the (for or while loop) loop it is in, even before the condition is met; this provides a way to terminate the loop within the middle of the body
Continue - terminates the current iteration of the loop and goes back to the header; “continues” to the next iteration of the loop
Pass - null statement; used as placeholders when user doesn’t want any code to execute; in contrast to a comment which is ignored by the interpreter, a pass is not ignored although nothing happens when a pass is executed; user can place pass where empty code is not allowed, like in loops, function definitions, class definitions, or in if statements to avoid error
Else - executed when the loop terminates through exhaustion of the iterable or when the condition becomes false, but not when the loop is terminated by a break statement
List comprehensions are a shorter way of running ‘for loop’ on lists
syntax is [<expression> for <element> in <list> if <boolean>]
offers a concise syntax and can perform the combined operation of any filter() and map() functions into one line
a ‘for loop’ would have required creating a new empty list to append to while looping through the elements in the old list