Effective Python memo Item 7 Use list comprehension instead of map and filter

Notes on Effective Python

Item 5: Use list comprehension instead of map and filter (p15 ~ 16)

In most cases, comprehensions are cleaner and easier to read than using higher-order functions

Higher-order functions are functional and cool (?), But they generate lambdas one by one, so it's difficult to read unless you're used to it. Guido seems to dislike higher-order functions in the first place, and there will be a limited number of situations where he will actively use them.

If you can use the inclusion notation, write it in the inclusion notation!

Example of squaring a sequence

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#Write an expression that squares each sequence

# map()in the case of
squares = map(lambda x: x ** 2, a)
print(list(squares))

>>>
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

#In case of inclusion notation
squares = [x ** 2 for x in a]
print(squares)

>>>
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

The latter is easier to see, isn't it? Let's add a condition to extract only even numbers.

#Only even numbers are squared and extracted

# map()And filter()If you write in
even_squares = map(lambda x: x**2, filter(lambda x: x % 2 == 0, a))
print(list(even_squares))

>>>
[4, 16, 36, 64, 100]

#In case of inclusion notation
even_squares = [x **2 for x in a if x % 2 == 0]
print(even_squares)

>>>
[4, 16, 36, 64, 100]

This is clearer! There is no room for hesitation

By the way, not only lists but also dictionaries and sets can be used for inclusion notation.

#Invert dictionary keys and values, create new dictionaries
chile_ranks = {'ghost': 1, 'habanero': 2, 'cayenne': 3}
rank_dist = {rank: name for name, rank in chile_ranks.items()}
chile_len_set = {len(name) for name in rank_dist.values()}
print(rank_dist)
print(chile_len_set)

>>>
{1: 'ghost', 2: 'habanero', 3: 'cayenne'}
{8, 5, 7}

Summary

Higher-order functions aren't bad, but it's better to write your code for readability. (Except for those who really like functional programming ...)

Recommended Posts

Effective Python memo Item 7 Use list comprehension instead of map and filter
EP 7 Use List Comprehensions Instead of map and filter
Effective Python Memo Item 3
Effective Python Memo Item 11 Use zip to process iterators in parallel
Python comprehension (list and generator expressions) [additional]
Effective Python memo Item 10 Enumerate from range
Summary of how to use Python list
Effective Python Memo Item 8 Avoid three or more expressions in list comprehensions
I measured the speed of list comprehension, for and while with python2.7.
Effective Python Memo Item 18 Use variable-length positional arguments to make the appearance cleaner
Compare the speed of Python append and map
python development environment -use of pyenv and virtualenv-
Python> Comprehension / Comprehension> List comprehension
List of Python code to move and remember
I compared the speed of the reference of the python in list and the reference of the dictionary comprehension made from the in list.
filter, map, reduce with js and python (There are also arrow expressions, lambda expressions, comprehension expressions)
Mayungo's Python Learning Note: List of stories and links
List of Python libraries for data scientists and data engineers
Use urlparse.urljoin instead of os.path.join for Python URL joins
Python Exercise 2 --List Comprehension
List of python modules
Filter List in Python
Ruby, Python and map
Python3 List / dictionary memo
[Memo] Python3 list sort
Effective Python Note Item 20 Use None and the documentation string when specifying dynamic default arguments
[Python of Hikari-] Chapter 08-03 Module (Import and use of standard library)
Learn "English grammar" instead of Python and AI related English words. .. ..
[Road to intermediate Python] Use if statement in list comprehension
Comparison of how to use higher-order functions in Python 2 and 3
Python: Create a dictionary from a list of keys and values
Effective Python Note Item 16 Consider returning a generator without returning a list
python memo: enumerate () -get index and element of list at the same time and turn for statement
[Python] Correct usage of map
Summary of Python3 list operations
Python and ruby slice memo
Operation of filter (None, list)
Use and integration of "Shodan"
[Python] Copy of multidimensional list
Python list and tuples and commas
Python list comprehensions and generators
Source installation and installation of Python
I want to use both key and value of Python iterator
List of Linear Programming (LP) solvers and modelers available in Python
python note: map -do the same for each element of the list