for
loops are traditionally used when you have a block of code which you want
to repeat a fixed number of times. The Python for statement iterates over the
members of a sequence in order, executing the block each time. In this blog,
except for for
loop’s syntax and flow diagram, I’ll also talk about how to
achieve loops over:
- a range
- a string
- a
numpy array
- a list
- a list of lists
- a dictionary
- a series
- a dataframe
Syntax
Flow diagram
If a sequence
contains an expression list, it is evaluated first. Then, the
first item in the sequence
is assigned to the iterating variable
iterating_var
. Next, the statements
block is executed. Each item in the
list is assigned to iterating_var
, and the statement(s)
block is executed
until the entire sequence
is exhausted.
Loop of a range
Loop of a string
Loop of a numpy array
The iterator object nditer
provides many flexible ways to visit all the
elements of one or more arrays in a systematic fashion.
Loop of a list
enumerate
is a built-in function of Python. It allows us to loop over
something and have an automatic counter.
Loop of a list of lists
Loop of a dictionary
Remark:
dict.items()
returns iterator object. dict.iteritems()
is removed in
python3.
Loop of a series
Both pandas.Series.items
and pandas.Series.iteritems
lazily iterate over
(index, value) tuples.
Loop of a dataframe
pandas.DataFrame.iterrows
iterates over dataFrame rows as (index, Series)
pairs.
Conclusion
In this blog, we talked about syntax of for
loop, and its applications: loop
over a range, loop over a string, loop over a numpy array, loop over a list,
loop over a dictionary, loop over a series and loop over a dataframe. Hope it’s
useful for you :)
Reference
- SciPy.org, Iterating Over Arrays, viewed 29 January 2019, https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html#arrays-nditer.
- PythonTips, Enumerate, viewed 29 January 2019, http://book.pythontips.com/en/latest/enumerate.html.
- pandas 0.24.0 documentation, pandas.Series, viewed 29 January 2019, https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.html.
- pandas 0.24.0 documentation, pandas.DataFrame.iterrows, viewed 29 January 2019, https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html.
- tutorialspoint, Python for Loop Statements, viewed 7 February 2019, http://www.tutorialspoint.com/python/python_for_loop.htm.