Getting heavier operations done using built-in functions and other smart functions is a known advantage of Python.
Today, I show 3 quick one liners that are often asked in interviews as well. Let’s go!
- Swapping objects:
With Python, you don’t need to declare a separate temporary variable to hold one of the variable to be swapped.
Just reassign them to each other’s objects and you are done!
- Flattening a 2-D list:
I declare a nested list which essentially is 2-D. To flatten it out, I can write 2 nested For loops and append the elements to a new list.
The same operation can be done in a single line using list comprehension with nested For loops!
- Calculating Factorial:
Now before you point it out, this is just another way for calculating factorials. Not the only one.
Coming to the point, we can use the reduce function from functools module for a smart calculation.
What it does is, it takes a function and a list as inputs.
The function here is a lambda function which just calculates multiplication of 2 integers.
Passing it to reduce iteratively calculates the multiplication of each integer with the output of previous multiplication.
Sweet! isn’t it?
Comment down what all one liners you use !
#python #datascience #datascience