5
votes

What is the preferred way to tell someone "I want to apply func to each element in iterable for its side-effects."

# Option 1... clear, but two lines.
for element in iterable:
    func(element)

# Option 2... even more lines, but could be clearer.
def walk_for_side_effects(iterable):
    for element in iterable:
        pass

walk_for_side_effects(map(func, iterable))  # Assuming Python3's map.

# Option 3... builds up a list, but this how I see everyone doing it.
[func(element) for element in iterable]

I'm liking Option 2; is there a function in the standard library that is already the equivalent?

2
You should use option 1. It's the one that best communicates that your code is imperative, and doesn't construct a useless result list. - millimoose
map and the list comrehension are equivalent. The walk_for_side_effects call is useless. Use option 1. - Pavel Anossov
@PavelAnossov: Not in python 3; map() returns an iterator. - Martijn Pieters♦
Technically, Option 1 could be done in one line as for element in iterable: func(element). It's against PEP8 style, but I would say that using list comprehensions to generate a list that is never used is a worse offense. - David Robinson
@MartijnPieters: man, I need to work more with Python 3 :( - Pavel Anossov

2 Answers

8
votes

Avoid the temptation to be clever. Use option 1, it's intent is clear and unambiguous; you are applying the function func() to each and every element in the iterable.

Option 2 just confuses everyone, looking for what walk_for_side_effects is supposed to do (it certainly puzzled me until I realized you needed to iterate over map() in Python 3).

Option 3 should be used when you actually get results from func(), never for the side effects. Smack anyone doing that just for the side-effects. List comprehensions should be used to generate a list, not to do something else. You are instead making it harder to comprehend and maintain your code (and building a list for all the return values is slower to boot).

2
votes

This has been asked many times, e.g., here and here. But it's an interesting question, though. List comprehensions are meant to be used for something else.

Other options include

  1. use map() - basically the same as your sample
  2. use filter() - if your function returns None, you will get an empty list
  3. Just a plain for-loop

while the plain loop is the preferable way to do it. It is semantically correct in this case, all other ways, including list comprehension, abuse concepts for their side-effect.

In Python 3.x, map() and filter() are generators and thus do nothing until you iterate over them. So we'd need, e.g., a list(map(...)), which makes it even worse.