10 Powerful Python One-Liners

10 Powerful Python One-Liners

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

#1. if-else ternary operator:

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

# 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"

namel[::-1]

print(name)
# 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)

print(a)
# Output: 1

print(b)
# Output: [2, 3, 4, 5]

#5. lambda function:

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

add(2+1)
# Output: 3

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

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

add(2,3)
# 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):
    nums.append(number)

print(nums)
# Output: [1, 2, 3, 4]

Above code can be simplified into this:

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

print(nums)
# 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}

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

#9. generator expression:

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

gen=fruit_generator()

next(gen)
# 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'])

next(gen)
# 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!