I need to process lots of data in lists and so have been looking at what the best way of doing this is using Python.
The main ways I’ve come up with are using:
– List comprehensions
– generator expressions
– functional style operations (map,filter etc.)
I know generally list comprehensions are probably the most “Pythonic” method, but what is best in terms of performance?
Inspired by this answer: Python List Comprehension Vs. Map , I’ve tweaked the questions to allow generator expressions to be compared:
For built-ins:
For lambdas:
Making a list:
It appears that
mapis best when paired with built-in functions, otherwise, generator expressions beat out list comprehensions. Along with slightly cleaner syntax, generator expressions also save much memory over list comprehensions because they are lazily evaluated. So in the absence of specific tests for your application, you should usemapwith builtins, a list comprehension when you require a list result, otherwise a generator. If you’re really concerned with performance, you might take a look at whether you actually require lists at all points in your program.