[PYTHON] Judgment of if by list comprehension

If you use list comprehensions, you can use if to exclude elements that you don't want to include in the resulting list. For example, the following code

[ x for x in [1, 2, 3, ] if x > 2]

This way, the resulting list will only contain 3. At this time, there is a case where the function is applied to x and it is desired to perform filtering by the applied value. For example, the following code

def f(x):
    x = x * 2
    return x

[ f(x) for x in [1, 2, 3, ] if f(x) > 2]

This way, the resulting list will contain 4, 6. ~~ The important thing is that in these cases method f is only executed once for each element. ~~ -> This part is incorrect.

Recommended Posts

Judgment of if by list comprehension
List comprehension
List comprehension
List of packages installed by conda
Judgment of igneous rock by machine learning ②
Python> Comprehension / Comprehension> List comprehension
Note: List comprehension
Get a list of Qiita likes by scraping
Search by the value of the instance in the list
List of python modules
FizzBuzz in list comprehension
Copy of multiple List
Python list comprehension speed
Add a list of numpy library functions little by little --a
List of activation functions (2020)
Not just list comprehension
Depth of nested list
Group by consecutive elements of a list in Python
Display of fractions (list)
If ... else in comprehension
colaboratory List of library versions included by default Memo
Quicksort 2 | Easy list comprehension
[Python] How to make a list of character strings character by character
Add a list of numpy library functions little by little --c
[Road to intermediate Python] Use if statement in list comprehension
Negative / positive judgment of sentences and visualization of grounds by Transformer
Negative / positive judgment of sentences by BERT and visualization of grounds
Summary of Python3 list operations
Operation of filter (None, list)
List of nodes in diagrams
List of self-made Docker images
Visualization of data by prefecture
Calculation of similarity by MinHash
Multidimensional array initialization of list
[Python] Copy of multidimensional list
List of useful coding styles
[Python] Display only the elements of the list side by side [Vertical, horizontal]
If you give a list with the default argument of the function ...
Learning by ABC173C (bit full search, copying of multidimensional list, one-dimensionalization of multidimensional list)