Lambda keyword for anonymous methods

Python uses the lambda keyword to define in-line or anonymous methods. It's mostly used when you want method behavior (e.g. input variables and scope protection), but want to: avoid declaring a full-fledged method with def because the logic is too simple; want to minimize written code; or want to keep the logic in a single location.

Similar to list comprehensions which are not essential but are widely used to simplify iteration logic, the lambda keyword is also not essential but is widely used to incorporate method like behavior with a simpler syntax. To get accustomed to the lambda keyword, when you see a statement like lambda x: <logic_on_x> just make the mental transformation to def anon_method(x): <logic_on_x>.

Listing A-23 illustrates various lambda examples based on past examples.

Listing A-23 Python lambda examples

country_codes = ['us','ca','mx','fr','ru']
zipcodes = {90003:'Los Angeles',90802:'Long Beach',91501:'Burbank',92101:'San Diego',
                                                 92139:'San Diego',90071:'Los Angeles'}
# Map function with lambda
country_codes_upper_map = [*map(lambda x: x.upper(),country_codes)]

# Filter function with lambda 
zip_codes_la_filter_lambda_dict_items = [*filter(lambda location: location[1] == "Los Angeles", zipcodes.items())]
zip_codes_la_filter = [tup[0] for tup in zip_codes_la_filter_lambda_dict_items]

The examples in listing A-23 are very similar to the map() and filter() examples in listing A-22, except they use lambda statements (i.e. anonymous methods) to perform the logic on each container.