Chapter 9. Other Features of the Language

In this chapter you are introduced to some other aspects of Python that are less frequently used, as well as modules that are very commonly used. Each section describes at least one way that the feature is typically used and then offers example code.

In previous chapters you looked at some common functions, and even learned to create your own. Part of the charm of Python is its breadth of built-in functions and modules that cater to both broad and obscure problems. Before learning to build your own module, you look at some of the ones Python offers to get a better understanding of their usage.

In this chapter you learn:

  • To work with the lambda and filter functions.

  • To use map to avoid loops.

  • To string substitutions.

  • The getopt module.

Lambda and Filter: Short Anonymous Functions

Sometimes you need a very simple function invocation — something that is not generally useful or that is so specific that its use needs to be completely different if it is invoked in another location in your code. For these occasions, there is a special operation: lambda. Lambda is not a function itself but a special word that tells Python to create a function and use it in place, rather than reference it from a name.

To demonstrate lambda being used, the following example uses filter, which is a function that enables you to take a list and remove elements based on criteria you define within a function you write. Normal functions can be used, but in simple cases, such as ...

Get Beginning Python®: Using Python 2.6 and Python 3.1 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.