Powerful One-Liner Python codes

Python is a widely-used general-purpose, high-level programming language. Python programs generally are smaller than other programming languages like Java. Programmers have to type relatively less and indentation requirements of the language makes them readable all the time. However, Python programs can be made more concise using some one-liner codes. These can save time by having less code to type.

Refer to the below articles to know more about Python.

One-Liners in Python

One-Liner #1: To input space separated integers in a list:



Suppose you want to take space separated input from the console and you want to convert it into List. To do this map() function can be used that takes int() method and input().split() methods as parameter. Here the int() method is used for conversion of input to int type and input().split() methods are used to take input from the console and split the input by spaces. Below is the implementation.

filter_none

edit
close

play_arrow

link
brightness_4
code

lis = list(map(int, input().split()))

chevron_right


Note: To know more about Python map() function click here.

One-Liner #2: To input a 2-D matrix(When the entries are given row-wise):

The most naive method that comes in mind while taking a input for 2-D matrix is given below.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Input for row and column
R = int(input()) 
C = int(input()) 
  
matrix = [] 
  
# for loop for row entries 
for i in range(R):          
    a =[] 
  
    # for loop for column entries 
    for j in range(C):
         a.append(int(input())) 
    matrix.append(a) 

chevron_right


The above code can be written in one-line that is way more concise and saves time especially for competitive programmers.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Input for row and column
R = int(input())
C = int(input())
  
# Using list comprehension for input
matrix = [[int(input()) for x in range (C)] for y in range(R)] 

chevron_right


One-Liner #3: We know this fact, but sometimes we tend to ignore it while translating from other languages. It is swapping of two numbers. The most naive way of doing this is:

filter_none

edit
close

play_arrow

link
brightness_4
code

temp = a
a = b
b = temp

chevron_right


However, Python provides one-liner for this also. The Pythonic way is:

filter_none

edit
close

play_arrow

link
brightness_4
code

# to swap two numbers a and b
a, b = b, a

chevron_right


One-Liner #4 Lambda Functions(Anonymous Functions) – Lambda functions are python one liner functions and are often used when an expression is to be evaluated.

For example, let’s suppose we want to create a function that returns the square of the number passed as argument. The normal way of doing this is:

filter_none

edit
close

play_arrow

link
brightness_4
code

def sqr(x):
    return x * x
  
print(sqr(5))

chevron_right


Output:


25

Lambda function replaces a function wherever a single expression is to be evaluated.

filter_none

edit
close

play_arrow

link
brightness_4
code

sqr = lambda x: x * x
print(sqr(5))

chevron_right


Output:

25

One-Liner #5 List comprehensions – This is a concise way to create lists. Instead of doing it the usual way, we can make use of list comprehensions.

For example, we want to create a list of even numbers till 11. The normal way of doing this is:

filter_none

edit
close

play_arrow

link
brightness_4
code

evenNumbers =[]
for x in range(11):
    if x % 2 == 0:
        evenNumbers.append(x)
  
print(evenNumbers)

chevron_right


Output:

[0, 2, 4, 6, 8, 10]

The pythonic way:

filter_none

edit
close

play_arrow

link
brightness_4
code

evenNumbers =[x for x in range(11) if x % 2 == 0]
print(evenNumbers)

chevron_right


Output:

[0, 2, 4, 6, 8, 10]

One-Liner #6: This trick may help while using if-else or while loop. Instead of doing this –

filter_none

edit
close

play_arrow

link
brightness_4
code

if m == 1 or m == 2 or m == 3:
    pass

chevron_right


We can code it as:

filter_none

edit
close

play_arrow

link
brightness_4
code

if m in [1, 2, 3]:
    pass

chevron_right


One-Liner #7: There are various ways to reverse a list in python.
Pythonic ways to reverse a list:


  • Using the slicing technique- This technique creates the copy of the list while reversing. It takes up more memory.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    lis = [1, 2, 3]
    reversed_list = lis[::-1]
      
    print(reversed_list)

    chevron_right

    
    

    Output:

    [3, 2, 1]
    
  • Using the reverse function- It reverse the contents of the list object in-place.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    lis = [1, 2, 3]
    lis.reverse()
      
    print(lis)

    chevron_right

    
    

    Output:

    [3, 2, 1]
    
  • One-Liner #8: You can take this as a challenge. Making one-liner python patterns.

    For example, Make the following code concise to one line.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    for i in range(0, 5): 
            
            for j in range(0, i + 1): 
                # printing stars 
                print("* ", end ="") 
             
            # ending line after each row 
            print("\r")

    chevron_right

    
    

    Output:

    * 
    * * 
    * * * 
    * * * * 
    * * * * * 
    

    Concise all this in one line is fun.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    n = 5
      
    # one liner code for half pyramid pattern
    print('\n'.join('* ' * i for i in range(1, n + 1)))

    chevron_right

    
    

    Output:

    * 
    * * 
    * * * 
    * * * * 
    * * * * *
    

    One-Liner #9 Finding the factorial. The normal way of finding a factorial is iterating till that number and multiplying the number in each iteration.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    n = 5
    fact = 1
        
    for i in range(1, n + 1): 
        fact = fact *
    print (fact) 

    chevron_right

    
    

    Output:

    120
    

    We can use math.factorial(x)– It returns the factorial of x. But it raises Value error if number is negative or non-integral.


    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    import math
      
      
    n = 5
    print(math.factorial(n))

    chevron_right

    
    

    Output:

    120
    

    One more way to do find the factorial concisely is by using reduce() and lambda function.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    import functools
      
      
    n = 5
    print(functools.reduce(lambda x, y: x * y, range(1, n + 1)))

    chevron_right

    
    

    Output:

    120
    

    One-Liner #10: Finding all subsets of a set in one line.
    Usual way takes a lot of hard work and can be seen here. It can be be done in a much simpler way using itertools.combinations()

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    from itertools import combinations
      
      
    # list of all subsets of 
    # length r (r = 2 in this example) 
    print(list(combinations([1, 2, 3, 4], 2)))

    chevron_right

    
    

    Output:

    [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
    

    One-Liner #11: Read file in python and input it to a list.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    file = open('gfg.txt', 'r'
    lis =[]
      
    for each in file:
      
        # removing '\n' from the end of the string
        a = each[:-1
        lis.append(a)
      
    file.close()

    chevron_right

    
    

    One liner code is:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    lis = [line.strip() for line in open('gfg.txt', 'r')]

    chevron_right

    
    



    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


    Article Tags :

    3


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.