Check out these lesser-known Python features

divmod

This is a very useful function. Thedivmod()function performs a modulus division%on two numbers, then returns both the quotient and remainder. For example:

Out:(2, 1)

This is simply finding the number of times we can fit2into5, without splitting the number, which gives us2, the quotient. After this, we still have1leftover, which is our remainder.

This is particularly useful for returning the time taken for a process to run — in hours, minutes, and seconds. Like so:

*args, **kwargs

Occasionally, you may notice that a function definition contains these two arguments, likedef func(x, y, *args, **kwargs).

They’re both incredibly simple features and allow us to pass multiple values to a function, which will then be packed into a generator.

It has a similar outcome as if we passed a list/generator to a standard argument:

Out:‘1 2 3 '

Now, let’s use*args— this will allow us to pass each value as a new argument, rather than containing them all within a list.

Out:1 2 3

Note that we didn’t need to typeargs. Instead, we typedvalues. The variable name we use is irrelevant. It is defined as anargs, thanks to the single asterisk.

*argssimply creates a tuple from the arguments we pass into a function.

**kwargson the other hand, creates a dictionary. Hence the name,key-wordarguments. We use it like so:

Again, we can call the variable whatever we want. In this case, we usedvalues. It is defined as akwargsby the use of a double asterisk**.

Comprehensions

This is definitely one of the most useful features of Python. Comprehension expressions are unmissable. The most common is thelist comprehension. I’m sure the vast majority of you will have seen these:

Out:[1, 4, 9, 16, 25]

But we are not limited to those square brackets. We can define agenerator expressionwith almost the exact same syntax:

Out:<generator object at 0x7f0281730fc0>

Of course, each element in the generator will only be output when called, which we can do withlist():

Out:[1, 4, 9, 16, 25]

With another small change of syntax, we can even build dictionaries usingdictionary comprehensions:

casefold

This string method is particularly interesting. It functions in a similar way tolower. However,casefoldattempts to standardize, more aggressively, a wider range of characters.

In most cases,lowerandcasefoldbehave the same, but occasionally, they do not:

In comparison, usinglower:

Here, both sigmas are already lower-case. Depending on the use-case, it may function as expected.

However, if we intended to compare two equivalent Greek words, one using σ and the other ς, onlycasefoldwould allow us to compare them accurately:

Story byJames Briggs