DEV Community

Enes ARSLAN
Enes ARSLAN

Posted on

20 Extremely Useful Single-Line Python Codes

1.One-line For Loop

For loops are multi-line statements, but in Python, we can write for loops in one line using list comprehension methods. As an example, to filter out values less than 250, take a look at the following code example.

#For loop in one line
mylist = [200, 300, 400, 500]
#Single line For loop
result = [] 
for x in mylist: 
    if x > 250: 
        result.append(x) 
print(result) # [300, 400, 500]
#One-line code way
result = [x for x in mylist if x > 250] 
print(result) # [300, 400, 500]
Enter fullscreen mode Exit fullscreen mode

2 .One-Line While Loop

This One-Liner segment will show you how to use While loop code in one line, with two different methods demonstrated.

#Method 1 Single Statement   
while True: print(1) #infinite 1  
#Method 2 Multiple Statements  
x = 0   
while x < 5: print(x); x= x + 1 # 0 1 2 3 4 5
Enter fullscreen mode Exit fullscreen mode

3 .One-Line IF Else Statement

Alright, to write an IF Else statement in one line we will use the ternary operator. The syntax for the ternary is “[on true] if [expression] else [on false]”.

I have shown 3 examples in the sample code below to make it clear to you on how to use the ternary operator for a one-line if-else statement. To use an Elif statement, we must use multiple ternary operators.

#if Else In a single line.  
#Example 1 if else  
print("Yes") if 8 > 9 else print("No") # No  
Enter fullscreen mode Exit fullscreen mode
#Example 2 if elif else   
E = 2   
print("High") if E == 5 else print("数据STUDIO") if E == 2 else   
print("Low") # Data STUDIO 
Enter fullscreen mode Exit fullscreen mode
#Example 3 only if  
if 3 > 2: print("Exactly") # Exactly
Enter fullscreen mode Exit fullscreen mode

4.Merging dictionaries in one line

This one-liner code segment will show you how to merge two dictionaries into one using a single line of code. Here, I’ve presented two methods for merging dictionaries.

# Merging dictionaries in one line  
d1 = { 'A': 1, 'B': 2 }   
d2 = { 'C': 3, 'D': 4 }  
#Method1   
d1.update(d2)   
print(d1) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}  
#Method2   
d3 = {**d1, **d2}   
print(d3) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}
Enter fullscreen mode Exit fullscreen mode

5. One-Line Function

There are two ways we can write a function in one line, in the first method we will use the same function definition as with the ternary operator or one-line loop method.

The second method is to use lambda to define the function. Take a look at the example code below for a clearer understanding.

#Function in one line  
#Method1
def fun(x): return True if x % 2 == 0 else False   
print(fun(2)) # False  
#Method2
fun = lambda x : x % 2 == 0   
print(fun(2)) # True   
print(fun(3)) # False
Enter fullscreen mode Exit fullscreen mode

6.Recursion in one line

This single-line code snippet will show you how to use recursion in one line. We will use a one-line function definition and a one-line if-else statement. Here is an example for finding the Fibonacci numbers.

# Single-line recursion 
#Fibonaci Single-line recursion example  
def Fib(x): return 1 if x in {0, 1} else Fib(x-1) + Fib(x-2)  
print(Fib(5)) # 8  
print(Fib(15)) # 987
Enter fullscreen mode Exit fullscreen mode

7.Filtering an array in one line

Filtering an array in one line of code using Python lists can be done using the list comprehension method. An example of filtering an even number list is shown.

# Filtering arrays in a single line  
mylist = [2, 3, 5, 8, 9, 12, 13, 15]  
#Normal way  
result = []   
for x in mylist:   
    if x % 2 == 0:   
        result.append(x)  
print(result) # [2, 8, 12]  
# One-line method  
result = [x for x in mylist if x % 2 == 0]   
print(result) # [2, 8, 12]
Enter fullscreen mode Exit fullscreen mode

8.Exception Handling in One Line

We use exception handling to handle runtime errors in Python. Did you know that we can write the Try except statement in one line? By using the exec() statement, we can do this.

# Exception handling in one line  
#Original method  
try:  
    print(x)  
except:  
    print("Error")  
#Single line way  
exec('try:print(x) \nexcept:print("Error")') # Error
Enter fullscreen mode Exit fullscreen mode

9.Converting a list to a dictionary in one line

Convert a list to a dictionary in one line using the Python enumerate() function. Pass the list to enumerate() and use dict() to convert the final output to dictionary format.

# Dictionary in one line  
mydict = ["John", "Peter", "Mathew", "Tom"]  
mydict = dict(enumerate(mydict))  
print(mydict) # {0: 'John', 1: 'Peter', 2: 'Mathew', 3: 'Tom'}
Enter fullscreen mode Exit fullscreen mode

10.One-Line Multiple Variables

Python allows for multiple variable assignments in one line. The following example code will show you how to do this.

#Multiple variable assignments in one line.  
#Single-line method  
x = 5   
y = 7   
z = 10   
print(x , y, z) # 5 7 10  
#Single line way  
a, b, c = 5, 7, 10   
print(a, b, c) # 5 7 10
Enter fullscreen mode Exit fullscreen mode

11.Swapping values in one line

In one line, exchange values. Swapping is a fun task in programming, and it always requires a third variable name, temp, to save the swapped value. This one-line code snippet will show you how to swap values in one line without any temporary variables.

#Swap values in one line  
#Single-line method 
v1 = 100  
v2 = 200  
temp = v1  
v1 = v2   
v2 = temp  
print(v1, v2) # 200 100  
# One-line value swapping 
v1, v2 = v2, v1   
print(v1, v2) # 200 100
Enter fullscreen mode Exit fullscreen mode

12.One-Line Sorting

Sorting is a common problem in programming, and Python has many built-in methods to solve this sorting problem. The code examples below will show how to sort in one line.

# Sort in one line  
mylist = [32, 22, 11, 4, 6, 8, 12]   
# Method1
mylist.sort()   
print(mylist) # # [4, 6, 8, 11, 12, 22, 32]  
print(sorted(mylist)) # [4, 6, 8, 11, 12, 22, 32]
Enter fullscreen mode Exit fullscreen mode

13.Reading a file in one line

You can correctly read a line of a file without using statements or the normal reading methods.

#Reading a file in one line  
#Single-line method 
with open("data.txt", "r") as file:   
    data = file.readline()   
    print(data) # Hello world  
#Single line way  
data = [line.strip() for line in open("data.txt","r")]   
print(data) # ['hello world', 'Hello Python']
Enter fullscreen mode Exit fullscreen mode

14.One-line class

Classes are always multi-line work. But in Python, there are ways to use class features in one line of code.

# One-line class  
#Regular way  
class Emp:   
    def __init__(self, name, age):   
        self.name = name   
        self.age = age  
        emp1 = Emp("a44", 22)   
print(emp1.name, emp1.age) # 
#Single line way  
#Method 1 Lambda with Dynamic Attributes 

Emp = lambda:None; Emp.name = "a44"; Emp.age = 22  
print(Emp.name, Emp.age) # 

#Method 2 
from collections import namedtuple  
Emp = namedtuple('Emp', ["name", "age"]) ("a44", 22)   
print(Emp.name, Emp.age)
Enter fullscreen mode Exit fullscreen mode

15.One-line semicolon

In this code snippet, the semicolon shows you how to use a semicolon to write multiple lines of code in a single line.
python

# One-line semicolon 
# exsample 1   
a = "Python"; b = "Programming"; c = "languages"; print(a, b, c)  
# print
# Python Programming languages
Enter fullscreen mode Exit fullscreen mode

16.One line print

This isn’t an important snippet, but it can be useful sometimes when you don’t need to use a loop to perform a task.

# One line print
#Single-line method
for x in range(1, 5):  
    print(x) # 1 2 3 4  
#Single line way  
print(*range(1, 5)) # 1 2 3 4  
print(*range(1, 6)) # 1 2 3 4 5
Enter fullscreen mode Exit fullscreen mode

17.One line map function

The map function is a useful higher-order function that applies a function to each element. Here is an example of how we can use the map function in one line of code.

#One line map function 
print(list(map(lambda a: a + 2, [5, 6, 7, 8, 9, 10])))  
# print
# [7, 8, 9, 10, 11, 12]
Enter fullscreen mode Exit fullscreen mode

18.Deleting the Mul elements from the first row of the list

You can now use the del method to delete multiple elements from a List in a single line of code, without any modification.

# Deleting the Mul elements from the first row of the list
mylist = [100, 200, 300, 400, 500]  
del mylist[1::2]  
print(mylist) # [100, 300, 500]
Enter fullscreen mode Exit fullscreen mode

19.One line print pattern

Now you no longer need to use a for loop to print the same pattern. You can use the print statement and asterisk (*) to do the same thing in a single line of code.

# One line print pattern#   
# Single-line method  
for x in range(3):  
    print('😀')  
# print
# 😀 😀 😀  
#Single line way  
print('😀' * 3) # 😀 😀 😀   
print('😀' * 2) # 😀 😀   
print('😀' * 1) # 😀
Enter fullscreen mode Exit fullscreen mode

20.Find primes in a range in a single line of code

This code snippet will show you how to write a single line of code to find the prime numbers within a range.

# Find primes in a range in a single line of code
print(list(filter(lambda a: all(a % b != 0 for b in range(2, a)),  
                  range(2,20))))  
# print
# [2, 3, 5, 7, 11, 13, 17, 19]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)