Over the last few weeks, there have been a few interesting features that I myself recently learned about. Here is a quick look at these features, and a rundown of each. [Read: A look at the best new features in Python 3.9] [Out]: (2, 1) This is simply finding the number of times we can fit 2 into 5 , without splitting the number, which gives us 2, the quotient. After this, we still have 1 leftover, 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:
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 type *args. Instead, we typed *values. The variable name we use is irrelevant. It is defined as an *args, thanks to the single asterisk *.
*args simply creates a tuple from the arguments we pass into a function.
**kwargs on the other hand, creates a dictionary. Hence the name, key-word arguments. We use it like so:
Again, we can call the variable whatever we want. In this case, we used **values. It is defined as a **kwargs by the use of a double asterisk **.
[Out]: [1, 4, 9, 16, 25]
But we are not limited to those square brackets. We can define a generator expression with almost the exact same syntax:
[Out]: <generator object
This article was originally published on Towards Data Science by James Briggs, an AI Consultant based in London. He is fascinated by the phenomenal advances that are being made within the tech eco-system daily and loves writing about AI, Python, and programming in general. Follow him on Twitter.