5 Python tricks to level up your code!

Josiah Brown
3 min readDec 20, 2022

Are you looking to up your Python game and make your code more efficient? Look no further! Here are five cool Python tricks that will not only improve the efficiency of your code but also impress your friends and colleagues (assuming they’re into that kind of thing).

1. Use List Comprehensions

Instead of using a for loop to populate a list, you can use list comprehensions to do it in a much more concise way. For example, say you want to create a list of the squares of the numbers 0 through 9. Here’s how you could do it with a for loop:

squares = []
for i in range(10):
squares.append(i**2)

It takes 3 lines of code to make something like this! But with list comprehensions, it can be done on a single line. Here’s how we can do the same thing with a list comprehension.

squares = [i**2 for i in range(10)]

Not only is the list comprehension version shorter and easier to read, but it’s also faster to execute. Win-win!

2. Use the “ternary operator” to write concise if-else statements

The ternary operator (also known as the conditional operator) is a way to write an if-else statement in a single line of code. Here’s an example of a traditional…

--

--