25 Useful Python One-Liners That You Should know

In this blog, I want to present some python one-liners which everyone should know.

1. Swapping Two Variables

# a = 4 b = 5
a,b = b,a
# print(a,b) >> 5,4

Let’s start with a simpler one by swapping two variables with each other. This method is one of the most simple and intuitive methods that you can write with no need to use a temp variable or apply arithmetic operations.

2. Multiple Variable Assignments

a,b,c = 4,5.5,'Hello'
#print(a,b,c) >> 4,5.5,hello

You can use commas and variables to assign multiple values to the variables at a time. Using this technique, you can assign multiple data types var at a time. You can use a list to assign values to variables. Below is an example of assigning multiple values to different var from a list.

a,b,*c = [1,2,3,4,5]
print(a,b,c)> 1 2 [3,4,5]

3. Sum of Even Numbers In a List

There can be many ways of doing this, but the best and simplest way is to use the list indexing and sum function.

a = [1,2,3,4,5,6]
s = sum([num for num in a if num%2 == 0])
>> 12

4. Deleting Multiple Elements from a List

del is a keyword used in python to remove values from a list.