AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |
Back to Blog
![]() The lambda keyword allows us to declare small, anonymous, single-line functions, taking one or more parameters and returning a value of an expression. A really simple concept with a fancy name, lambda functions or simply lambdas are a syntactic sugar in Python. The key thing to unpack here is key=lambda movie: movie - what exactly is going on here? Lambda functions - what are they?įirst we need to understand what a lambda is. This will get us the following ordering of movies (note the descending ordering of ratings) (1994, 'The Shawshank Redemption', 9.2) movies = sorted(movies, key=lambda movie: movie, reverse=True) Let's use this knowledge to sort our movies by rating, in descending order. The value of the key parameter should be a function (or other callable) that takes a single argument and returns a key to use for sorting purposes. The official Python docs explain this in simple terms: Both list.sort() and sorted() have a key parameter to specify a function (or other callable) to be called on each list element prior to making comparisons. Python's sorted function offers a simple solution - use the key parameter. In our previous example, what if we wanted to sort the movies by rating first, then by year? Understanding how lists of tuples or lists of lists are sorted is crucial to understanding more complex sorting patterns - those using the key parameter. Note that sorted always sorts in ascending order unless we modify its behaviour using key or reverse parameters.
0 Comments
Read More
Leave a Reply. |