A Flavor of Python

Explore adding a flavor of Python into C++.

We'll cover the following

In this lesson, I want to perform a small experiment. Can I add a flavor of Python into C++?

The programming language Python has the convenient functions filter and map.

  • filter: applies a predicate to all elements of an iterable and returns those elements for which the predicate returns true
  • map: applies a function to all elements of an iterable and returns a new iterable with the transformed elements

An iterable in C++ would be a type that you could use in a range-based for loop. Furthermore, Python lets you combine both functions in a list comprehension.

  • list comprehension: applies a filter and map phase to an iterable and returns a new iterable

Here is my challenge: I want to implement Python-like functions filter, and list comprehension in C++20 using the ranges library.

Note: The map function is left for you as an exercise.

filter function

Python’s filter function can be directly mapped to the corresponding ranges function.

Get hands-on with 1400+ tech skills courses.