I’m looking to write a function that takes the integers within a list, such as [1, 2, 3], and returns a new list with the squared integers; [1, 4, 9]
How would I go about this?
PS – just before I was about to hit submit I noticed Chapter 14 of O’Reilly’s ‘Learning Python’ seems to provide the explanation I’m looking for (Pg. 358, 4th Edition)
But I’m still curious to see what other solutions are possible
You can (and should) use list comprehension:
mapmakes one function call per element and whilelambdaexpressions are quite handy, usingmap+lambdais mostly slower than list comprehension.Python Patterns – An Optimization Anecdote is worth a read.