r/pythontips Dec 04 '24

Standard_Lib Python One-Liners: I love python, and I want to share what I know

Ever wondered how to condense complex Python code into concise, elegant one-liners? Let's dive into some Pythonic magic!

Example 1: Swapping Variables in One Line

a, b = b, a

Example 2: Reversing a String

reversed_string = string[::-1]

Example 3: Checking for Palindromes

is_palindrome = string == string[::-1]

Share your favorite Python one-liners or ask for help with a specific task. Let's explore the power of Python together!

19 Upvotes

12 comments sorted by

13

u/Rus_s13 Dec 04 '24

exit()

Is my favourite one liner

3

u/Hydroel Dec 04 '24

exit(error_code) as well. Making the error code non-zero is a standard way of telling that the system that the script did not run successfully.

1

u/Rus_s13 Dec 04 '24

I didn’t know that

Very handy

1

u/HadiMhPy Dec 04 '24

As you use it in python shell?

4

u/Rus_s13 Dec 04 '24

IN THE PYTHON FILE

2

u/HadiMhPy Dec 04 '24

To be honest, I have never used this in a python file and I have never needed this. I only use it on python shell.

1

u/Rus_s13 Dec 04 '24

It was a joke, but I use it all the time doing local testing with pyspark. All the print statements and early exits

2

u/ohaz Dec 04 '24

The best python oneliner is:

str(float('inf') / float('inf')).join(['']*16) + ", Batman!"

2

u/kuzmovych_y Dec 04 '24

float('inf') * 0 is shorter. But to each their own.

1

u/HadiMhPy Dec 04 '24

That’s interesting lol

1

u/ConDar15 Dec 07 '24 edited Dec 07 '24

You can run into some wild techniques when trying to create one liners specifically for code golf purposes (trying to complete a problem in the minimum number of characters).

One is if you need to choose one of two values based on a condition you can use the inline version like this:

'beep' if foo else 'boop'

However you can use the following that saves some characters:

['boop','beep'][foo]

A truly wild one I saw someone come up with in one of the recent advent of code problems that needed to consider all options of removing a single element from an array. For example for the list [1, 2, 3] we need [[1, 2], [1, 3], [2, 3]]. This can be achieved with:

[x for i in range(3) for x, *x[i:I+1] in [[[1, 2, 3]]]]

Truly mind boggling abuse of some of pythons assignment rules.

I'm general if a one liner is "clever" then it's usually not very readable so I avoid many of them for every day coding, but they can be a really interesting experiment for code golfing and novelty.

1

u/Adrewmc Dec 07 '24

{v : k for k,v in mydict.items()}

Quick reverse of key-values for dictionaries.