Home >Backend Development >Python Tutorial >Is Using List Comprehensions for Side Effects in Python Considered Bad Practice?
Using List Comprehensions for Side Effects: A Non-Pythonic Practice
Python's list comprehensions are powerful tools for creating new lists based on existing iterables. While they offer concise and expressive syntax, using list comprehensions solely for their side effects is considered anti-Pythonic.
The Problem
Consider a function that performs side effects such as printing to the screen, updating a GUI, or writing to a file. It returns a value, but the value is typically not of interest.
def fun_with_side_effects(x): ...side effects... return y
One might be tempted to use a list comprehension to call this function for its side effects, as follows:
[fun_with_side_effects(x) for x in y if (...conditions...)]
Note that the resulting list is not assigned to a variable.
The Anti-Pythonic Nature
Using list comprehensions in this manner is strongly discouraged for several reasons:
The Preferred Approach
The preferred approach is to use a for loop to iterate over the iterable and call the side-effecting function only when necessary:
for x in y: if (...conditions...): fun_with_side_effects(x)
This approach is more efficient, idiomatic, and less confusing. It is a clear indication that the function is being called primarily for its side effects.
The above is the detailed content of Is Using List Comprehensions for Side Effects in Python Considered Bad Practice?. For more information, please follow other related articles on the PHP Chinese website!