Iterations in Python: for loop, list comprehension, and map
Wed Jan 18, 2017 · 4 min read
Wed Jan 18, 2017 · 4 min read
I’ve been working in Python 3 for about a week, and so far greatly enjoy it. To me, learning code syntax (and programming in general) amounts to an amalgamation of lego blocks: once it’s understood what a certain color of block does, it’s straightforward to combine them to create the structure you’re looking for.
That said, some blocks can be a little confusing at first. I found documentation relating to iteration in Python to be a little hard to digest, mostly because of subtle differences in terminology: iteration, iterator, iterating, iterable… it’s enough to make your eyes glaze over. I found concrete examples to be most useful in learning these concepts; this post aims to summarize what I’ve learned.
There are a few different ways to achieve iterations in Python. I’ll present some of these ways in this post and discuss appropriate situations for each.
for iterating_var in iterable: statement/statements
For loops are handy things. They’re straightforward to understand, which is especially helpful if you’re reading someone else’s code and trying to follow their thought process. They can achieve as much or as little as you need, and each operation can be clearly written out.
iterating_var can be any of Python’s data types: a letter in a string, an item from a list, an index from a list, integers, etc. An
iterable can also take different forms: a string of word(s), a range of numbers, a list, and so on. A
statement or multiple
statements indicates doing something: anything from mathematical expressions to simply printing a result. Check out the following examples, which simply print each
iterating_var of an
iterable on a new line:
for letter in 'Hello world': print(letter) for i in range(10): print(i) breakfastmenu = ['toast','eggs','waffles','coffee'] for choice in breakfastmenu: print(choice)
arrstring = ' '.join(str(e) for e in arr)
The downside to for loops is that they can be a bit verbose, depending on how much you’re trying to achieve. Still, for anyone learning Python or hoping to make their code as easily understood as possible, for loops are still the most straightforward choice for iterations.
newlist = [statement/statements for iterating_var in iterable]
In my opinion, list comprehensions are the most elegant of the solutions discussed in this post. Once you have a grasp of how they work, you can perform concise and effective iterations with very little code.
List comprehensions will always return a list, which may or may not be appropriate for your situation. If appropriate, however, simply defining the variable name of the list can often help you skip some steps.
For example, I can use list comprehension to quickly calculate and print tip percentage on a few bar tabs at once:
tabs = [23.60, 42.10, 17.50] tabsplustips = [round(tab*1.15, 2) for tab in tabs] print(tabsplustips) >>> [27.14, 48.41, 20.12]
In one concise line, we’ve taken each tab amount, added 15% tip, rounded it to the nearest cent, and made a new list of the tabs plus the tip values.
List comprehensions can be an elegant tool, depending on the variety of statements you want to iterate through, and whether or not output to a list is useful to you. The more statements you add, the more complicated your list comprehension begins to look, especially once you get into nested list comprehensions. If your code isn’t well annotated, it may become difficult for another reader to figure out.
Map is, in many ways, a non-idiomatic function for iteration in Python. It’s pretty compact, which can make it easy to write improperly with a missing comma or parenthesis, and it’s more limited than for loops or list comprehensions in its usage. Basically, it applies your
statement to every instance of your defined
I used the map function in my solution to HackerRank’s 10 Days of Statistics - Day 0: Weighted Mean challenge. In this example, it’s casting each element of
input() (the iterable) from string representation to integer representation.
values = list(map(int, input().split())) weights = list(map(int, input().split())) output = sum([x * x for x in zip(values, weights)]) / sum(weights) print(round(output, 1))
It’s worthwhile to note that map by itself returns an iterator; if it’s a list you want, it’s an extra step to get the list representation, as in the example above.
In truth, I’ve had a hard time coming up with appropriate situations for the use of map over simply using a list comprehension. Aside from situations similar to the above, it seems to me to be a rather un-Pythonic way to iterate. It can be advantageous as a concise method of doing simple, sort of ‘on-the-spot’ iterations; otherwise, my preference would be to use a list comprehension instead.
I hope these examples have been useful to you in your understanding of iterations with Python 3. Thanks for reading!