Little Known Python Functions

This article will describe the little-known, but useful, Python functions. Many of the functions on this list can greatly reduce your code, optimize it, and make it more readable.

Filter function

The filter function is designed to “filter” an array and can replace a loop. Filter works faster than a loop, in some cases the speed of the program increases tenfold when using filter instead of classical loops.

The filter function takes as input:

  1. Another function that returns True or False

  2. The list, the elements of which will be fed to the input of the function

The function passed to filter must contain a condition that defines the criteria for the elements of the new array. If the function returns True – the element is added to the new array, if False – the element is not added.

The filter function returns an object of the Filter class, use list () to transform it into an array.

Filter helps you make your code more streamlined and readable.

For example, you are given an array a, you need to write all numbers that are less than 10 into array b and display it on the screen.
How it looks without using filter:

a = [1, 10, 24, 6, 8, 19]
b = []
for i in range(len(a)):
	if a[i] < 10:

Using filter, it looks like this:

a = [1, 10, 24, 6, 8, 19]
b = list(filter(lambda x: x< 10, a))

The code looks more concise and works faster.

Map function

The map function, like the filter function, can replace loops. Loops are slower than map, but not every loop can be replaced with map.

The map function takes as input:

  1. The function that is passed each element of the array

  2. Array

Each element of the array is fed to the input of the function. The final array is formed from the values ​​returned by the function.

The map function allows you to make your code prettier and speed up its work.

For example, let’s take a problem that I often have. You need to read 5 numbers entered through a space from the keyboard and display their sum on the screen. Since a string is read from the keyboard, not numbers, it is necessary to convert them all to numbers.

Example without using map:

a = input().split(" ")
b = []
for i in range(5):

Program using map:

a = list(map(int, input().split(" ")))

The program using map is smaller and faster, but it can be made even faster with the following function.

Reduce function

The reduce function works the same as map, but reduce only returns one value from the last execution of the passed function. Before using reduce, it must be imported from the functools module.

The reduce function receives as input:

  1. A function that receives more than one value

  2. An array whose elements will be passed to the input of the function

Reduce passes an array element and the output of the previous execution to the function input; during the first execution, the first array elements are passed to the function.

For example, let’s take the problem we looked at last time.

An example without reduce:

a = list(map(int, input().split(" ")))

An example using reduce:

from functools import reduce
def summa(a, b):
	return a+b
print(reduce(summa, list(map(int, input().split(" ")))))

In this case, the program has become larger and not much faster, this shows that it is necessary to analyze how appropriate the use of such functions is. In other cases, the program will be optimized and scaled down.

The sets

Sets is a data type that works faster than others, but cannot have duplicate elements. To create a set, the set () function is used, which is passed a string, an array, and so on. Sets have methods and new operators:

  1. add () – add an item to a set

  2. discard () – remove an element from a set

  3. union () – unites the set from which the function is called, with the one that is passed as an argument

  4. intersection () – finds the intersection of the sets from which it is called, with the one that is passed as an argument

  5. difference () – finds all elements that are in the set from which the function is called, but which are not in the set passed as an argument

  6. symmetric_difference () – Returns a set that contains all elements from two sets, except for their common elements

  7. isdisjoint () – returns True if both sets have no elements in common, and False if they have

  8. | – the same as union

  9. & is the same as intersection

  10. – (minus) – same as difference

  11. ^ – same as symmetric_difference

Sets have a wide range of uses, even for excluding identical elements from an array. Lots can help you make your code faster and add new features.

Any and all functions

The any and all functions are used instead of the OR and AND operators. They allow you to shorten your code and make it more readable when you use a large number of conditions in your program.

They both take an array of conditions or booleans as an argument, and return a single boolean value.

Any – replaces the OR operator, if there is at least one True in the arguments, the output will be True.

All – replaces the AND operator, if the arguments contain at least one False, the answer will be False.

For example, let’s take a program that should print “1” if there are identical variables, and “-1” if there are none. Then it should check if the first variable is equal to the second and the second to the thirds, if so, print “2”.

Example without any and all:

a = input()
b = input()
c = input()
d = input()
if (a == b) OR (a == c) OR (a == d) OR (b == c) OR (b == d) OR (c == d):
if (a==b) AND (c == d):

Example using any and all:

a = input()
b = input()
c = input()
d = input()
if any([(a == b), (a == c), (a == d), (b == c), (b == d), (c == d)]):
if all([(a==b), (c == d)]):

The code has become nicer to the eye and slightly smaller, these functions are appropriate to use if you use a large number of conditions for one if or while statement.

That’s all, I hope you learned something new. If I missed something, then write in the comments, if there are many little-known Python tricks, then I will release the second part.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *