5 Useful Advanced Features of Python

Python is a popular and beautiful programming language used in data science, web development, maths, and so on. In addition to learning the basics, there are lots of easy-to-understand advanced Python features you need to know.

By advanced, I don’t mean hard. These topics are really important but not crucial when learning the basics of Python.

Today I’m going to show 5 common advanced topics/features in Python that you should learn.

I hope you enjoy it.

1. Lambda Functions

In Python, a lambda function is an anonymous function (a nameless function) that can take any number of arguments. It can only contain a single expression.

For instance, here is a lambda that multiplies a number by four:

lambda x : x * 4

To use this lambda, you can assign it to a variable:

mult4 = lambda x : x * 4
mult4(15.0) # returns 60

Or you can call it right away:

(lambda x : x * 4)(15.0) # returns 60.0

Lambda functions are useful when the functionality is needed for a short while. In such a case, you don’t want to waste resources by creating a separate method.

Lambda Example

Let’s filter a list of numbers using the built-in filter() method. It takes two parameters:

  • A filtering function (a lambda function in this case)
  • A list to be filtered

As an example, let’s filter even numbers:

numbers = [1, 2, 3, 4, 5, 6]

filtered_numbers = list(filter(lambda x : x % 2 == 0 , numbers))

print(filtered_numbers)

Output:

[2, 4, 6]

2. Mapping

Mapping in Python is a convenient way to transform a group of values into another. To map items in Python, use the built-in map() function.

The map() function is a replacement to a for a loop. It applies a function for each element of e.g. a list. The map() function accepts two arguments:

  • A function that is applied for each element in the list (for example a lambda expression)
  • A list on which to operate

The map() function returns a map object. This can easily be converted back to e.g. a list with the list() function.

To demonstrate this, let’s square a list of numbers:

numbers = [1, 2, 3, 4, 5]

# Compute the squares
squares = map(lambda x: x ** 2, numbers)

print(list(squares))

Output:

[1, 4, 9, 16, 25]

3. Filtering

The filter() function, as the name suggests, can be used to filter elements based on a specific condition. The filter function takes two arguments:

  • A lambda expression i.e. a function that is executed for each element in the list
  • A list to operate on

For instance, let’s filter even numbers from a list:

numbers = [1, 2, 3, 4, 5, 6]

# filter even numbers
even_nums = filter(lambda x: x % 2 == 0, numbers)

print(list(even_nums))

Output:

[2, 4, 6]

4. Itertools

An iterator is an object that is used to iterate over iterable objects like lists, tuples, dictionaries, etc.

Itertools is a really useful module in Python. It lets you perform memory-efficient tasks on the iterators (such as lists, dictionaries, tuples, etc.).

Generate Infinite Sequences with Itertools

Using Itertools it is programmatically possible to generate an infinite sequence of evenly spaced numbers using the count() method. As such, the code below creates an infinite sequence of numbers 0, 1, 2, 3, ... .

import operator
import itertools

for n in itertools.count():
    print(n)

Output:

1
2
3

...

Notice you can tweak the initial value and the step size. For instance, to create an infinite sequence of 100, 102, 104, 106, ...:

import operator
import itertools

for n in itertools.count(100, 2):
    print(n)

Generate All Possible Combinations

You can use the Itertools combinations() function to create all the possible combinations there are. For instance:

import operator
import itertools

items = ['a', 'b', 'c']
permutations = itertools.permutations(items)

for group in permutations:
    print(group)

Output:

('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')

These are just some highlights of using Itertools. For further knowledge, check out the rest of the useful functions provided by Itertools module.

5. Generators

In Python, you can use a generator to create your own iterator function. A generator is a ‘special function’ that doesn’t return a single value. Instead, it returns an iterator object with a sequence of values instead of yielding values. Thus, in a generator function a yield keyword is used instead of return.

Due to lazy evaluation, generators are really memory-efficient. This makes them useful when dealing with huge amounts of data.

Example

For instance, here is a simple generator function:

def mygenerator():
    print('1st item')
    yield 1

    print('2nd item')
    yield 2

    print('3rd item')
    yield 3

Now, this generator can be used as follows:

generator = mygenerator()

next(generator)
next(generator)
next(generator)

Output:

1st item
2nd item
3rd item

For Loops and Generators

You can create a generator function that uses for loops. For example:

def generate_up_to(n):
    for i in range(n):
        print("Generated number ", i)
        yield i

generator = generate_up_to(5)

next(generator)
next(generator)
next(generator)
next(generator)
next(generator)

Output:

Generated number  0
Generated number 1
Generated number 2
Generated number 3
Generated number 4

Generator Expressions to Improve Code Readability

You may also what is known as generator expression (similar to list comprehension) to make the generator function shorter.

For instance, let’s repeat the above generator example with the help of a generator expression. This way you don’t need to write a separate generator function at all.

n = 5
generator = (print("Generated number ", i) for i in range(n))

next(generator)
next(generator)
next(generator)
next(generator)
next(generator)

Output:

Generated number  0
Generated number 1
Generated number 2
Generated number 3
Generated number 4

Conclusion

That’s it for the advanced Python features.

There are many more useful features that we did not cover in this guide. But the ones you learned today are important and very commonly used. So make sure to digest it well!

Thanks for reading.

Happy coding!

Further Reading

Useful Python Tips and Tricks