[PYTHON] EP 7 Use List Comprehensions Instead of map and filter

  • List comprehensions are clearer than the map and filter built-in functions because they don't require extra lambda expressions.

Effective Python

>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> squres = [x ** 2 for x in a]
>>> squres
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

>>> squres_map = map(lambda x: x ** 2, a)
>>> list(squres_map)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

map requies creating a lambda function for the computation, which is visually noisy.

>>> even_squares = [x ** 2 for x in a if x % 2 == 0]
>>> even_squares
[4, 16, 36, 64, 100]


>>> even_squares_fp = map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, a))
>>> list(even_squares_fp)
[4, 16, 36, 64, 100]

Dicts and sets comprehensions

>>> chile_ranks = dict(ghost=1, habanero=2, cayenne=3)
>>> rank_dict = {rank:name for name, rank in chile_ranks.items()}
>>> rank_dict
{1: 'ghost', 2: 'habanero', 3: 'cayenne'}
>>> chile_len_set = {len(name) for name in rank_dict.values()}
>>> chile_len_set
{8, 5, 7}

Recommended Posts

EP 7 Use List Comprehensions Instead of map and filter
Effective Python memo Item 7 Use list comprehension instead of map and filter
Operation of filter (None, list)
Use and integration of "Shodan"
Python list comprehensions and generators
Let's use usercustomize.py instead of sitecustomize.py
Let's use tomotopy instead of gensim
Use Bucket (). Objects.filter instead of list_objects_v2 when outputting S3 list with Boto3
R: Use Japanese instead of Japanese in scripts
List of Atom packages I really use
Summary of how to use Python list
EP 16 Consider Generator Instead of Returning Lists
[For beginners] Simple sample of list operation functions map, reduce, filter for each language
List of frequently used built-in functions and methods
Compare the speed of Python append and map
python development environment -use of pyenv and virtualenv-
List of Python code to move and remember
Data cleansing 3 Use of OpenCV and preprocessing of image data
EP 4 Write Helper functions Instead of Complex Expressions