Photo by Emile Perron onUnsplash
Python is a general-purpose language widely used by developers due to its ease of use and rich API. However, once you're comfortable with Python, it's important to explore its advanced features to help you be more productive and write more efficient code. This article introduces 5 advanced features of Python that can help you achieve this.
map
function is a built-in Python method that allows you to apply a function to every item in an iterable (e.g. list, tuple, etc.). This function is highly optimized, making it an excellent tool for improving the performance of our code.
Here's an example of using for loops and a function to apply to items in an array:
def double(x):return 2 * xnumbers = [1, 2, 3, 4]doubled_numbers = []for number in numbers:doubled_numbers.append(double(number))print(doubled_numbers)
Now we're goint to use the map function but frist we should break it down to its parameters and return
This is how we invoke the map function:
result = map(function, array)
function
is the function to be applied to all items in the arrayarray
is the iterable that will mutate depending on function
It is worth mentioning that the map
function will not return an iterable itself but rather a generator. In order to unpack it we can wither cast result
to a list
result = list(map(function, array))
Here's the compact version using the map
and lambda
approach:
numbers = [1, 2, 3, 4]doubled_numbers = list(map(lambda x: 2 * x, numbers))print(doubled_numbers)
This code outputs:
[2, 4, 6, 8]
As we can see, the map and lambda approach is more concise and easier to read, making it a valuable tool in our Python toolkit.
The filter function is another built-in Python function that is used to filter items in an iterable based on a specified condition. This function is highly optimized and can be used to reduce the amount of code needed to perform a filter operation.
Here's an example of using a for loop and if statements to filter items in an array:
numbers = [1, 2, 3, 4, 5]even_numbers = []for number in numbers:if number % 2 == 0:even_numbers.append(number)print(even_numbers)
Here's the compact version using the filter built-in function:
numbers = [1, 2, 3, 4, 5]even_numbers = list(filter(lambda x: x % 2 == 0, numbers))print(even_numbers)
This code outputs:
[2, 4]
The reduce
function is another great function that comes with the core Python installation. However, this method is part of the functools module, therefore we'll need to import it if we intend to use it. Reduce might sound familiar to those of you who come from javascript, in fact, the methods do share the same functionality in that this function is used to apply a function to the items in an iterable so as to reduce the iterable to a single value
Here's a detailed explanation of the syntax of the reduce function:
reduce(function, iterable, initializer=None)
function
This is the function that will be applied to the items in the iterable
. It must take two arguments and return a single value.Iterable
This is the iterable (collection) that will be reduced.Initializer
(optional): This is the initial value that will be passed to the function
as its first argument. If not specified, the first item in the iterable will be used as the initial value (much like the initial accumulator value in javascript).Here's an example of reducing an iterable without the reduce
function:
from operator import mulfrom functools import reducenumbers = [1, 2, 3, 4, 5]product = 1for number in numbers:product *= numberprint(product)
Here the same snippet of code using the reduce
function:
from functools import reducenumbers = [1, 2, 3, 4, 5]product = reduce(lambda x, y: x * y, numbers)print(product)
This is the ouput for both snippets
120
In summary, the reduce
function provides a more concise, performant, reusable, and abstract way of reducing an iterable to a single value compared to a for loop, making it an excellent tool for boosting our productivity as a Python developer.
The enumerate
function is a built-in function in Python that is used to add a counter to an iterable. It's commonly used to loop over a list or other iterable and keep track of the index of each element.
This is a great alternative to the usual arr[i]
approach, as it makes our intentions explicit. When we use the enumerate function, we know we will at some point reference the item in the current iteration
Here's an example of accessing an item inside a collection withouth using the enumerate
function:
fruits = ['apple', 'banana', 'cherry']for index in fruits:print(f"{index + 1}: {fruits[index]}")
And here's the same functionality implemented with enumerate
fruits = ['apple', 'banana', 'cherry']for index, fruit in enumerate(fruits):print(f'{index + 1}: {fruit}')
In both cases the output will be the following:
1: apple2: banana3: cherry
As we can see, the enumerate function provides a more concise and readable way of looping over an iterable and keeping track of the index of each element compared to using a for loop and manually incrementing a counter.
Whether it's an interview question or a problem on Leetcode, we've all come across some sort situation where we are essentially asked to find all permutations of a collection
There are many approaches to finding the permutations of a collection. My personal favorite, is doing so by using a recursive implementation
Here's the Python code to find all the permutations of an iterable without using external libraries
def permutations(data, i, length):if i == length:print(data)else:for j in range(i, length):data[i], data[j] = data[j], data[i]permutations(data, i + 1, length)data[i], data[j] = data[j], data[i]fruits = ['apple', 'banana', 'cherry']permutations(fruits, 0, len(fruits))
This works just fine, but why rely on our own implementation when we can use the built-in functionality that comes with the functools
module.
we can use the itertools.permutations
function from the itertools module to find all permutations of a collection without using for loops. The itertools.permutations function takes an iterable and a length as arguments and returns an iterable of all possible permutations of the elements in the iterable.
Here's an example of how we might use the itertools.permutations
function:
import itertoolsfruits = ['apple', 'banana', 'cherry']permutations = list(itertools.permutations(fruits))for permutation in permutations:print(permutation)
The output is the same for both implementations:
('apple', 'banana', 'cherry')('apple', 'cherry', 'banana')('banana', 'apple', 'cherry')('banana', 'cherry', 'apple')('cherry', 'apple', 'banana')('cherry', 'banana', 'apple')
By understanding the built-in functions and libraries available in Python, we can simplify and streamline our code, reducing the amount of time and effort required to write and maintain it