The script in the previous part included very limited and basic use of functions. They were not returning anything, and they were quite simple. I also wasn't using any lambdas (which in Python mean simple, anonymous functions defined in a specific way). So let's take a look at a little illustrative program, showing how to define and call a function in Python, how to pass a parameter to it and return a value, how to pass a function as a parameter and how to define and use a lambda (in our case, passed as a parameter).
Once again, some programming experience may be needed to understand what's going on - the code below is just some simple examples of basic language constructions. This time: functions and lambdas. Some details in the comments. In the further part (below), one more notion regarging lambdas. For now, it's much less practical than the code in the first part, but I wanted to simply show (and note for myself) some basic syntax and use cases. Still not object-oriented.
The result of this running this code looks as follows:
Note on lambdas in Python
The code in Listing 1 shows use of lambda in Python. The last call in the main:
show_first_10_values(lambda arg: arg*arg))
is the call to a function, which takes another function as a param and calls it 10 times, with arguments from 1 to 10. I think that, although not very practical itself, it shows more-or-less how to use lambdas.
Meanwhile, there is a common example of using such lambdas in Python, which, although technically correct, doesn't make much sense:
First of all - this code works. It prints a number 6 in that case. But the problem is:
What's the point of using lambda here, if it's basically a function? The same code could look like this:
... or even like this (please note it's the same code, just one code indentation is ommited):
... and well, that's what functions are for, right?
Such practice, although quite common in various articles on lambdas in Python, seems to be criticized in the official Python style guide.
In the first example (Listing 1, show_first_10_values(lambda arg: arg*arg)), there is at least some reason of using a lambda: we need to pass some function as a parameter, and we want to define it ad hoc . Please note this:
show_first_10_values(lambda x: x*x)
is simply much shorter (and elegant) than this:
The next part: collections and data structures.
No comments:
Post a Comment