10 Powerful Python One-Liners

10 Powerful Python One-Liners

Pretty Python, let's promise to be together our whole life

Gaurav Sharma's photo
Gaurav Sharma
·May 19, 2022·

2 min read

Subscribe to our newsletter and never miss any upcoming articles

Play this article

#1. if-else ternary operator:

if 1==1 is True:

# Output: True

Above code can be written as:

print (True) if (1==1 is True) else print (False)

# Output: True

#2. Reverse a string in one line:

name = "VARUAG"


# Output: 'GAURAV'

#3. Read a file in one line code:

# Let's suppose filename is file.txt
print([print(line) for line in open("file.txt")])

#4. Tuple unpacking using asterisk(*):

a, *b = (1,2,3,4,5)

# Output: 1

# Output: [2, 3, 4, 5]

#5. lambda function:

def add(num1. num2) :
    print(num1 + num2)

# Output: 3

The above code can be converted into a lambda function as given below:

add = lambda num1, num2: print(num1 + num2)

# Output: 3

#6. Self calling lambda function:

The example given in above point can be also written in the form of self calling lambda:

# Syntax:
(lambda arg: returned value)(arg)

(lambda num1, num2: print (num1 + num2))(2+1)
# Output: 3

#7. list comprehension:

nums = []

for number in range(1,5):

# Output: [1, 2, 3, 4]

Above code can be simplified into this:

nums = [n for n in range(1,5)]

# Output: [1, 2, 3, 4]

#8. dictionary comprehension

fruits_list = ['mango', 'apple']
fruits_dict = {}

for fruit in fruits_list:
    fruits_dict[fruit] = fruit.upper()

print (fruits_dict)
# Output: {'mango': 'MANGO', 'apple': 'APPLE'}

The above code can be simplified into this:

fruits_list = ['mango', 'apple']

fruits_dict = {fruit: fruit.upper() for fruit in fruits_list}

# Output: {'mango': 'MANGO', 'apple': 'APPLE'}

#9. generator expression:

def fruit_generator():
    fruits = ['mango', 'apple', 'banana']
    for f in fruits:
        yield f


# Output: 'mango'

next (gen)
# Output: 'apple'

next (gen)
# Output: 'banana'

The above function code can be written with just a single line:

gen = (f for f in ['mango', 'apple', 'banana'])

# Output: 'mango'

next (gen)
# Output: 'apple'

next (gen)
# Output: 'banana'

#10. One line recursion using lambda:

# Factorial function using lambda function
fact = lambda n: 1 if n<1 else n * fac(n-1)

That’s it for today.

For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.

Did you find this article valuable?

Support Dev.Junction by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
Share this