11 Useful Python One-Liners You Must Know

11 Useful Python One-Liners You Must Know

Originally posted on makeuseof.

Python One-Liners can help you perform complex tasks with just one line of Python code. Here are some of the most useful ones to know!

Python is known for its short and clear syntax. Due to the simplicity of Python, it’s sometimes referred to as “executable pseudocode”. You can make Python programs more concise using one-liner codes. This will help you save time and write code in a more Pythonic way.

In this article, you’ll learn 11 Python one-liners that will help you code like a pro.

1. Convert String to Integer

You can convert a string to an integer using the inbuilt int() function.

str1 = '0'
str2 = '100'
str3 = '587'
print(int(str1))
print(int(str2))
print(int(str3))

Output:

0
100
587

2. Reverse a List

You can reverse a list in Python using various methods:

Using the Slicing Technique

Using this technique, the original list is not modified, but a copy of the list is created.

arr = [1, 2, 3, 4, 5, 6]
print(arr)
reversedArr = arr[::-1]
print(reversedArr)

Output:

[1, 2, 3, 4, 5, 6]
[6, 5, 4, 3, 2, 1]

Using the Inbuilt reversed() Function

The reversed() function returns an iterator that accesses the given list in the reverse order.

arr = [1, 2, 3, 4, 5, 6]
print(arr)
reversedArr = list(reversed(arr))
print(reversedArr)

Output:

[1, 2, 3, 4, 5, 6]
[6, 5, 4, 3, 2, 1]

Using the Inbuilt reverse() Method

The reverse() method reverses the elements of the original list.

arr = [1, 2, 3, 4, 5, 6]
print(arr)
arr.reverse()
print(arr)

Output:

[1, 2, 3, 4, 5, 6]
[6, 5, 4, 3, 2, 1]

3. Swap Two Variables

You can swap two variables using the following syntax:

variable1, variable2 = variable2, variable1

You can swap variables of any data type using this method.

a = 100
b = 12
print("Value of a before swapping:", a)
print("Value of b before swapping:", b)
a, b = b, a
print("Value of a after swapping:", a)
print("Value of b after swapping:", b)

Output:

Value of a before swapping: 100
Value of b before swapping: 12
Value of a after swapping: 12
Value of b after swapping: 100

4. FizzBuzz One-Liner in Python

The FizzBuzz challenge is a classic challenge that’s used as an interview screening device for computer programmers. You can solve the FizzBuzz challenge in just one line of code:

[print("Fizz"*(i%3==0)+"Buzz"*(i%5==0) or i) for i in range(1, 21)]

Output:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz

5. Generate Random Password

You can generate random passwords in Python using the following one-liner code:

import random as r; p = 'abcdefghijklmnopqrstuvwxyz0123456789%^*(-_=+)'; print(''.join([p[r.randint(0,len(p)-1)] for i in range(10)]))

Output:

v4+zagukpz

This code generates a password of length 10. If you want to change the length of the password, update the parameter of the range() function. Also, each time when you run the code, you’ll get a different random output.

6. Display the Current Date and Time in String Format

You can display the current date and time in Python using the datetime module. Here’s the one-liner code to display the current date and time in string format:

import datetime; print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

Output:

2021-11-22 14:35:41

7. Check if a String Is a Palindrome

A string is said to be a palindrome if the original string and its reverse are the same. You can check if a string is a palindrome or not using the following code:

str1 = "MUO"
str2 = "madam"
str3 = "MAKEUSEOF"
str4 = "mom"
print('Yes') if str1 == str1[::-1] else print('No')
print('Yes') if str2 == str2[::-1] else print('No')
print('Yes') if str3 == str3[::-1] else print('No')
print('Yes') if str4 == str4[::-1] else print('No')

Output:

No
Yes
No
Yes

8. Find Factorial of a Number

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. You can find the factorial of a number in one line of code using lambda functions.

num1 = 5
num2 = 0
num3 = 10
num4 = 12
factorial = lambda num : 1 if num <= 1 else num*factorial(num-1)
print("Factorial of", num1, ":", factorial(num1))
print("Factorial of", num2, ":", factorial(num2))
print("Factorial of", num3, ":", factorial(num3))
print("Factorial of", num4, ":", factorial(num4))

Output:

Factorial of 5 : 120
Factorial of 0 : 1
Factorial of 10 : 3628800
Factorial of 12 : 479001600

Fibonacci sequence is a series of numbers where each term is the sum of the two preceding ones, starting from 0 and 1. You can print the Fibonacci series up to n terms using the lambda function.

from functools import reduce; fibSequence = lambda n: reduce(lambda x, _: x+[x[-1]+x[-2]], range(n-2), [0, 1])
print(fibSequence(10))
print(fibSequence(5))
print(fibSequence(6))

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
[0, 1, 1, 2, 3]
[0, 1, 1, 2, 3, 5]

10. Calculate the Sum of a List

You can calculate the sum of a list using the sum() function in Python.

list1 = [1, 2, 3, 4, 5, 6, 7]
list2 = [324, 435, 456]
list3 = [0, 43, 35, 12, 45]
print(sum(list1))
print(sum(list2))
print(sum(list3))

Output:

28
1215
135

11. Sort a List

You can sort a list using the sort() method. Here’s the one-liner code for the same:

list1 = [12, 345, 123, 34, 23, 37]
list2 = ['m', 'a', 'k', 'e', 'u', 's', 'e', 'o', 'f']
list3 = [5, 4, 3, 2, 1]
print("Before Sorting:")
print(list1)
print(list2)
print(list3)
list1.sort()
list2.sort()
list3.sort()
print("After Sorting:")
print(list1)
print(list2)
print(list3)

Output:

Before Sorting:
[12, 345, 123, 34, 23, 37]
['m', 'a', 'k', 'e', 'u', 's', 'e', 'o', 'f']
[5, 4, 3, 2, 1]
After Sorting:
[12, 23, 34, 37, 123, 345]
['a', 'e', 'e', 'f', 'k', 'm', 'o', 's', 'u']
[1, 2, 3, 4, 5]

If you want to have a look at the complete source code used in this article, here’s the GitHub repository.

Write More Pythonic Code Using Built-In Methods and Functions

Inbuilt methods and functions help to shorten the code and increase its efficiency. Python provides many built-in methods and functions like reduce(), split(), enumerate(), eval(), and so on. Make use of all of them and write more Pythonic code.

 

Source: makeuseof