Convert `map(lambda x: expression, iterable)` to `(expression for x in iterable)`
See original GitHub issueDescription
map(f, iterable)
has great performance when f
is a built-in function, and it makes sense if your function already has a name. But if you need to introduce a lambda, it’s better (i.e., more readable and faster) to use a generator expression – no function calls needed.
Good:
for y in map(my_function_that_already_exists, it):
...
ys = list(map(my_function_that_already_exists, it))
ys = set(map(my_function_that_already_exists, it))
etc.
Suggestions:
# Bad:
map(lambda x: x**2, iterable)
# change to:
(x**2 for x in iterable)
# Bad:
list(map(lambda x: x.attr, iterable))
# change to:
[x.attr for x in iterable]
# OR change to:
y = list(map(operator.attrgetter("attr"), iterable))
# Bad:
z = map(lambda x: f(x), iterable)
# change to:
z = map(f, iterable)
Here are some perf numbers (deque(..., maxlen=0)
is a fast way to consume an iterable):
PS C:\Users\sween> py -3.8 -m pyperf timeit -s "from collections import deque" "deque(map(lambda x: -x, range(1_000_000)), maxlen=0)"
Mean +- std dev: 85.7 ms +- 1.7 ms
PS C:\Users\sween> py -3.8 -m pyperf timeit -s "from collections import deque" "deque((-x for x in range(1_000_000)), maxlen=0)"
Mean +- std dev: 63.1 ms +- 2.9 ms
Similar things hold for filter()
.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:7 (5 by maintainers)
Top Results From Across the Web
Python's map(): Processing Iterables Without a Loop
Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit...
Read more >Python map(function, iterable, ...) - LearnDataSci
Here, map() takes in three lists of different sizes and a lambda expression that concatenates three values using an f-string.
Read more >Apply a function to items of a list with map() in Python
Apply a function to items of a list with map() in Python. In Python, you can use map() to apply built-in functions, lambda...
Read more >Trying to solve with python map function with lambda ...
using map (map works on an iterable) n=10 fun=lambda x: (range(x)) # remember this is a function (so call it) fun=list(map(str, ...
Read more >4. Lambda Operator, filter, reduce and map - Python Courses eu
Chapter on the Lambda Operator and the functions map, filter and reduce.
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
This could also include
filter(lambda x: expression, iterable)
to(x for x in iterable if expression)
I can make a PR.