# Lambda Functions Aren’t Always Your Best Choices

## Don’t reinvent the wheels

`lambda arguments: expression`

## Operations Over Sequences

It’s a common task that we need to calculate the sum of the numbers in a sequence. Suppose that we have a math contest with each team having three members. Here are the records of their scores.

`>>> # Create a list of tuples for sorting>>> scores = [(95, 98, 99), (94, 97, 93), (95, 92, 93), (100, 95, 98)]`
`>>> # Sort the list with a lambda function>>> # The most tedious>>> sorted(scores, key=lambda x: x + x + x)[(95, 92, 93), (94, 97, 93), (95, 98, 99), (100, 95, 98)]>>> >>> # Slightly better>>> sorted(scores, key=lambda x: sum(x))[(95, 92, 93), (94, 97, 93), (95, 98, 99), (100, 95, 98)]`
`>>> # Best, using sum() directly>>> sorted(scores, key=sum)[(95, 92, 93), (94, 97, 93), (95, 98, 99), (100, 95, 98)]`
`>>> # Find out the team with the member having the highest score>>> # Using lambda>>> max(scores, key=lambda x: max(x))(100, 95, 98)>>> >>> # Using built-in directly>>> max(scores, key=max)(100, 95, 98)`

## Higher-Order Functions

We all probably know that functions are objects in Python. One implication is that functions can be used as arguments in other functions, and those functions that take other functions are termed higher-order functions, such as the built-in `map()` function.

`>>> # Create a list of numbers>>> numbers = [1, 2, 3, 4, 5]>>> >>> # Use the lambda with map()>>> squares0 = list(map(lambda x: x*x, numbers))>>> squares0[1, 4, 9, 16, 25]`
`>>> # Use the list comphrension>>> squares1 = [x*x for x in numbers]>>> squares1[1, 4, 9, 16, 25]`
`>>> # List comprehension with conditional>>> odds_squares = [x*x for x in numbers if x%2]>>> odds_squares[1, 9, 25]`

Written by

Written by

## Yong Cui, Ph.D.

#### Work at the nexus of biomedicine, data science & mobile dev. Love to write on these technological topics. Follow me @ycui01 on Twitter to get latest articles. 