Useful One-Liners In Python – A Quick Guide

FeaImg One Liners

Python is one of the most powerful and user-friendly programming languages ever created. Python is popular among programmers because it simplifies complicated tasks.

This tutorial will go through some easy and entertaining one-liners. Let’s get started!


Combine the contents of two dictionaries into a single one.

If you’re using Python3.9 or above, you may use | for this.

x = {'a': 11, 'b': 22}
y = {'c': 13, 'd': 44}
z = x | y
print(z)

The output looks like this:

{'a': 11, 'b': 22, 'c': 13, 'd': 44}

Get the most frequent element

Let’s utilize the most_common() function from the collections module to achieve this.

from collections import Counter
l = ['1', 'b', '2', 'a', '3', 'z', '3', 'a', '2', '3']
Counter(l).most_common()[0][0]

The code returns ‘3’ as the output which is correct!

Get quotient and remainder at the same time

divmod() returns a tuple and its functionality stems from the fact that it combines modulo percent and division/operators.

Q, R = divmod(35632, 5)
print("Quo. - ",Q)
print("Rem. - ",R)
Quo. -  7126
Rem. -  2

Find the first n Fibonacci numbers

This will be an excellent exercise on remembering lambda functions and recursion in Python.

fib = lambda x: x if x <= 1 else fib(x - 1) + fib(x - 2)
print(fib(20))
print(fib(5))
6765
5

Remove duplicate elements from a list

list(set(['1', '1', '2', '1', '3']))

In Python, each element in a set is unique, therefore there will be no duplicates.

['1', '3', '2']

Conclusion

Congratulations! You just learned 5 useful one-liners in the Python programming language. Hope you enjoyed it! 😇

Liked the tutorial? In any case, I would recommend you to have a look at the tutorials mentioned below:

  1. Tricks for Easier Debugging in Python
  2. Best Tips to Score Well in College Programming Assignment
  3. 3 Matplotlib Plotting Tips to Make Plotting Effective
  4. Competitive Programming in Python: What you need to know?

Thank you for taking your time out! Hope you learned something new!! 😄