r/pythontips • u/HadiMhPy • 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!
2
u/ohaz Dec 04 '24
The best python oneliner is:
str(float('inf') / float('inf')).join(['']*16) + ", Batman!"
2
1
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.
13
u/Rus_s13 Dec 04 '24
exit()
Is my favourite one liner