Python One Liners Trick Or Treat

Has
1 min readOct 12, 2022

--

Trick : Select Every Nth Item in a Sequence

string = "1*2*3*4*5"
print( string[::2] )
# 1234

Treat :

<<object>>[start:end:step] is a slicing method in python. Usually users are introduced to the object[start:end] part. The step is important in many scenarios as well.

Trick : Quick Simple Conditional Statement

selection = "trick"
ans = ("treats OwO", "tricked lol")[selection=="trick"]
print(ans)
# tricked lol

Treat :

(return_if_false, return_if_true)[conditional]

This works because True = 1 and False = 0, () represents a tuple in python where as [] is a way of accessing the elements of Tuple. So, in short if we evaluate that statement it would work like this.

(item0, item1)[0] which would yield item0 . If the conditional is true than it would select item1.

Trick : Increment / Decrement a Variable

Use -~n instead of n+1 and ~-n instead of n-1 and ~n instead of -n-1.

Treat :

~ is a binary inverse operator.

End Of Article.

If you have any cool tips please do share. I’ll update the article with time.

--

--

No responses yet