Python Tricks and Tips

silver laptop on brown wooden table

Here is a list of 10+ Python tricks and tips you can use to write cleaner code. I hope you enjoy it.

One-Liner If-Else in Python

Sometimes when an if-else expression is simple enough, it might actually be cleaner to write it as a one-liner:

isReady = False

# A regular if-else
if isReady:
    print("Yay")
else:
    print("Nope")
    
# A neat little shorthand
print("Yay") if isReady else print("Nope")

But be careful not to overdo this. It can make your code unreadable even when the intent is to make it cleaner.

Swap Two Variables without a Helper Variable

This is a classic interview question: How can you swap two variables without using a third helper variable?

Yes, it is possible by:

a = 1
b = 2

a, b = b, a

# Now a = 2 and b = 1

Chain Comparisons

Instead of doing two separate comparison conditions:

x > 0 and x < 200

You can chain them together as you do in maths:

0 < x < 200

One-Liner For-Loops in Python

You can use what is called a list comprehension to loop through a list neatly with one line of code.

For example, let’s square each number in a list of numbers:

numbers = [1, 2, 3, 4, 5]
[num * num for num in numbers]

The result:

[1, 4, 9, 16, 25]

Using comprehensions is not restricted to only lists.

You can use a similar syntax with dictionaries, sets, and generators too. For instance, let’s use dictionary comprehension to square values of a dictionary:

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
{ key: num * num for (key, num) in dict1.items() }

The result:

{'a': 1, 'b': 4, 'c': 9, 'd': 16}

Lambda Expressions—Write Shorter Python Functions

In Python, a lambda function is just a nameless function. It can take any number of arguments but can only have a single expression.

For instance, here is a lambda that multiplies a number by three:

lambda x : x * 3

Lambdas are useful when you need the functionality for a short period of time. A practical example is filtering a list. Python’s built-in filter method takes two parameters:

  • A filtering function (this is a lambda function)
  • A list to be filtered

As an example, let’s filter even numbers from a list by passing a lambda function into the filter() method to check if a number is even:

numbers = [1, 2, 3, 4, 5, 6]
list(filter(lambda x : x % 2 == 0 , numbers))

The result:

[2, 4, 6]

Repeat Strings without Using Loops

You can simply multiply a string by an integer to repeat it as many times as you prefer:

print("word" * 4)

Output:

wordwordwordword

How to Reverse a String in Python

sentence = "This is just a test"
sentence[::-1]

Result:

tset a tsuj si sihT

Simplify If-Statement Conditions

Would you agree that this looks pretty bad, even though there’s nothing wrong with it?

if n == 0 or n == 1 or n == 2 or n == 3 or n == 4 or n == 5:

Instead of this mess, you can make it look better by doing this:

if n in [0, 1, 2, 3, 4, 5]

Find the Most Frequent Element in a List in Python

To find the most frequently occurring element in a list, you can do:

max(set(nums), key = nums.count)

For example:

nums = [2, 2, 6, 2, 2, 3, 4, 2, 13, 2, 1]
max(set(nums), key = nums.count)

This gives you 2 as the most frequent number in the list.

Tear Values to Variables from a List

You can easily destructure list elements into separate variables.

For example:

arr = [1, 2, 3]
a, b, c = arr
print(a, b, c)

Output:

1 2 3

Use F-Strings to Format Strings in Python

With Python 3.6 and later, you can use F-Strings to embed expressions inside strings. As an example:

name = "Matt"
age = 25

sentence = f"Hi, I'm {name} and I'm {age} years old"
print(sentence)

Output:

H, I'm Matt and I'm 25 years old.

Simulate Coin Toss in Python

You can use the choice() method of the random module to pick random elements from a list.

For example, if you want to simulate tossing a coin, you can do:

import random
random.choice(['Head',"Tail"])

Join a List of Strings in Python

To join a list of strings, use the built-in join() method of a string.

For example:

words = ["This", "is", "a", "Test"]
print(" ".join(words))

Output:

This is a Test

Conclusion

Thanks for reading. I hope you find these Python tricks and tips useful

Happy coding!

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *