IntroductionYou've worked with both functions and methods, but there's a different type of function, the anonymous function. Anonymous functions are just functions without names, and in Python, they are handled with the lambda operator.
Anonymous functions allow you to use the behavior of a function without having to create a function. This is especially good when you only need to use a function once or twice. It might sound like an unusual occurrence, but it happens fairly frequently when a function or method takes a function as a parameter.
LambdasThe Lambda operator has a few basic parts. It consists of
lambda, a list of parameters, and an operation. The operation is separated from the other two with a colon. Check out this example.
foo = lambda a=2, b=1 : a / b
If you're using lambdas in a standalone capacity, you can set them equal to a variable. In this form, they aren't that versatile, but they can still play a role in creating functions on the fly.
Lambdas really find their use in being passed to other functions. See how it works in the example below.
def do_something(function, list_a, list_b):
for x in list_a:
for y in list_b:
do_something(lambda x, y : print(x*y), [1, 3, 5], [2, 4, 6])
Of course, this example isn't all that practical. It does illustrate the point, though. You can create a lambda within a function call to pass it as an argument to another function.
map() function is an interesting one. It allows you to iterate simultaneously over one or more lists and pass them to a function. It's very easy for that function to be a lambda expression.
This example can help clarify.
print(list(map(lambda x, y : x * y, [1, 2, 3, 4, 5], [2, 4, 6, 8, 10])))
That looks like a mess, so it's best to break it down. The main chunk starts with
map. It takes at least two arguments, a function and a list. It can take multiple lists, though, and this time there are two. It also takes a lambda expression that accepts two arguments and multiplies them together.
The map function runs through those lists. It sets each element in the first list in the first argument of the function and each element in the second list in the second function argument. It runs the function each time. The
map() function returns a map object.
That map object needs to be converted into a more usable form. The
list() function turns the object into a regular list. Then,
print() prints out that list.
Take a look at another one.
print(list(map(lambda x : x*2, [1, 2, 3, 4, 5])))
The simpler example might be easier to follow.
filter() function is another function similar to
map(). It takes a function and a list as arguments and iterates over the list, running the elements through the function.
Instead of just running a function,
filter() uses the function as a test condition for the elements in the list. The object that it creates contains all of the elements where the condition evaluated "True."
print(list(filter(lambda x : x > 5, [2, 4, 6, 8])))
The resulting list only contained 6 and 8 because those were the two conditions where the condition given in the function evaluated "True."
filter(), when used in conjunction with a lambda expression, is an efficient way to sort through and test lists against a condition.
Closing ThoughtsLambdas aren't the most popular topic in Python. Many developers don't even like them. Even Python's creator isn't a fan.
If you happen to like them, great. If not, don't worry. There are alternatives that will be discussed in later guides.
For now, it's just important to be aware of lambdas and how they work. You will encounter them from time to time, and they can be the easiest solution.
- Create a lambda expression that multiplies two numbers and set it equal to a variable.
- Use that variable to call the lambda and pass it two numbers.
- Write a function that takes a function as a parameter. Call that function with and pass it a lambda.
- Use the
map() function along with a lambda to add each element in two lists.
- Use the
filter() function along with a lambda to test if each element in a list is odd.
IntroductionJut about any program of a decent size needs to be able to read and write from files. At very least, it needs to be able to generate logs. Python is also tightly integrated into Linux system administration and scripting. Again, reading and writing are important for managing a system.
Opening A FilePython creates and object from the file that it opens. It can then manipulate that object. When it's done, it uses the object to save the any changes back to the file. Create a new text file and fill it with nonsense from your text editor. Be sure to include multiple lines of text. Now, create a Python file to work in. In that file, you can use Python's
open function to open the file and create an object with it.
file = open('test.txt', 'r+')
file is now an object that holds the information on the file. It can be both read and written. As you can see, the
open() function takes two arguments. The first is the path to the file that needs to be opened, and the second is the mode that it will be opened in. There are a number of modes, but there are only a few that you'll use frequently.
|Read ||r ||Only read from the file |
|Write> ||w ||Erase and write to a file |
|Append ||a ||Add new lines to the end of a file |
|Read & Write ||r+ ||Read and write to a file without overwriting it |
|Write & Read(Overwrite) ||w+ ||Write and read a file, overwriting its contents |
Reading A FileTake your file object for a test drive. Add a line in that calls the
file.read() The read method outputs the entire contents of the file into the command line. It's similar to using
cat. Reading the file shows each line as a string with a newline character at the end. The last line appears as an empty string,
There is another method that you can use to grab individual lines, the
readline() starts at the beginning of a file and reads each line out individually each time it is called.
Try removing the
read() line from your file and calling
readline() multiple times instead.
for x in range(1, 11):
If you had less than ten lines, you probably noticed a bunch of blank strings. That's what
readline() spits out whenever it goes beyond the number of lines in a file.
Writing A FileWriting to a file is even easier. All that you need to do to write to a file is call the
write() method and pass it the string that you want written to the end of the file.
write() will always write new lines to the end of the file.
file.write("I'm a new line!") You can write to a file as many times as you need to. Each time the
write() method is called, it creates a new line, making it ideal for logging.
SeekAs of now, you don't have any real control of the flow through the file. The
seek() method gives you some of that back.
It takes two numbers as arguments and allows you to move through the file in both directions. The first number is the position that you want the invisible pointer in the file to reverence. If you pass in a three, it'll be located after the third character. The second number is the place where you want it to start from. A value of 1 in the second place will cause the method to seek from he pointer's current position. A 2 would be then end of the file.
Python will print out from fifteen characters in to the end of the line where that point falls.
Closing the FileWhen you're done working with a file, you have to close it in order for changes to be applied and for memory to be freed up. You can cloe a file by calling the
close() method on the object.
Closing ThoughtsNow you can use Python to collect information from a file. You can also write output to a file. This opens up plenty of opportunity to use and store information from text files.
- Create a text file with at least 10 lines.
- In Python, open the file as both readable and writable without overwriting it.
- Read the file in Python.
- Reset the invisible pointer in the file to the beginning.
- Read only the first two lines of the file.
- Reset to the beginning again.
- Read only the seventh and ninth lines.
- Write two new lines to the file.
- Close your file.