Member-only story
5 Advanced Python Concepts: Explanations and Applications
Lambda functions, comprehensions, generators, decorators, and hashability
When you have developed a good understanding of basic data structures and their key functionalities, it’s time to explore some more advanced techniques in Python. In this article, I’d like to review five concepts that you can take advantage of in your code.
1. Lambda Functions
Lambda functions are also called anonymous functions in Python. Some people simply refer to them as lambdas. They have the following syntax: lambda arguments: expression
. In essence, we use the lambda keyword to signify the declaration of a lambda function. Then we list the arguments, the number of which can be zero or more. After the colon, we list the expression that uses these arguments for any applicable operations.
Lambda functions are particularly useful in cases where we need to have a short one-time use function. For instance, several built-in functions have the key argument, to which we can set a lambda function.
In the above code, we wanted to sort a list of tuples. By default, the tuples will be sorted based on each of the items contained. In this case, the sorting was based on the names’ first letters. However, we wanted to solve by the scores, which are the second items of the tuples. To accomplish it, we took advantage of the lambda function, in which the x
argument refers to each tuple that was to be sorted. Because the score was the second item in each tuple, we just needed to specify the index of 1 to access the second item.
2. Comprehensions
Probably the most Pythonic example that is mentioned a lot is the comprehension technique. In essence, this technique allows us to create a list, dictionary, or set using an exiting iterable, which are named list comprehension, dictionary comprehension, and set comprehension, respectively. The following code snippet shows you these usages.