10 Python Tips and Tricks with Explanations

Learn 10 awesome beginner-friendly Python coding “tricks” with in-depth explanations.

The following list is in no particular order.

I hope you enjoy it!

1. Swap Two Variables without a Third

In Python, it is possible to swap two variables without a third one:

a = 1
b = 2

a, b = b, a

Explanation

The above “trick” to swap two variables is not a trick at all. It uses destructuring (unpacking), which is a commonly used approach to unpack sequences of elements to separate variables.

In Python, it is possible to assign more than one variable at a time with a single line of code. To make this work, however, we need to make sure both sides have the same number of elements.

Here is a simple example of multiple assignments on the same line:

x, y = 10, 20

Now x is 10 and y is 20.

If you try to unpack an uneven number of values, say 3 values to 2 variables, there will be an error:

x, y = 10, 20, 30

Output:

ValueError: too many values to unpack (expected 2)

As you may already know, In Python, a comma-separated group of values is called a tuple.

In the above example:

x, y = 10, 20

We are actually unpacking the components of a tuple of (10, 20) into two separate variables. However, you may not be able to tell this as you commonly see tuples with parenthesis. This is because usually, you need to isolate the tuple from the surrounding code. So you could actually write the above example with parenthesis like this:

x, y = (10, 20)

So, now you know how tuple unpacking works.

This means you can now understand how the “trick” of swapping two variables without a third works.

a = 1
b = 2

a, b = b, a

All you do is create a tuple (b, a) and unpack it to variables a and b.

Lastly, it is useful to understand that unpacking is not restricted to tuples only. You can use it with lists as well.

For instance:

coords = [1, 5, 3]

x, y, z = coords

print(x, y, z)

Output:

1 5 3

This means you can use a list to swap two variables without a third:

a = 1
b = 2

a, b = [b, a]

2. Duplicate Strings without Loops

Similar to how you can multiply a number, you can multiply strings with the * operator in Python.

For instance:

name = "Banana"
print(name * 4)

Output:

BananaBananaBananaBanana

Explanation

String multiplication is quite intuitive in Python. The target string is repeated n times. In that sense, there is not much to add to the explanation. Instead, let’s jump into the details of what makes string multiplication possible in the first place.

If you are unfamiliar with double-underscore methods in Python, let the following be a little teaser to those.

Whenever you multiply a string, you are invoking a special method called __mul__ behind the scenes.

For example, this

name = "Banana"
print(name * 4)

Is equivalent to this:

name = "Banana"
print(name.__mul__(4))

What might not be surprising is that by default, Python classes do not support multiplication.

For example, let’s create a Fruit class and multiply a Fruit object:

class Fruit:
    name = "Banana"
    
# Example call
f = Fruit()
print(f * 4)

Output:

TypeError: unsupported operand type(s) for *: 'Fruit' and 'int'

However, you can make any Python class support multiplication by implementing a special method called __mul__.

For example, let’s make the Fruit class support multiplication in such a way that its name gets multiplied by a factor n:

class Fruit:
    name = "Banana"
    
    def __mul__(self, n):
        # Multiply the object's name by n
        return self.name * n

# Example call
f = Fruit()
print(f * 4)

This results in the following output:

BananaBananaBananaBanana

Notice that calling:

f * 4

Is shorthand for calling the __mul__ method you just implemented:

f.__mul__(4)

But why did I show you all of this?

A Python string is implemented by a class called str. Just like any other class, str would not support multiplication without implementing the __mul__ method. This means a Python string has a similar __mul__ method implemented in the str class as you saw in this example. This method is called under the hood whenever you multiply strings.

Meanwhile, this is not something you need to know if you are a beginner, it is still insightful knowledge.

However, the overall concept of double-underscore methods is something you need to learn over time. If you are unfamiliar with the double underscore methods (dunder methods), check out this awesome video to learn more.

3. Reverse a String

In Python, you can reverse a string with the following interesting-looking notation:

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

print(reversed)

Output:

tset a tsuj si sihT

Explanation

Reversing a string (or any other Python iterable) with [::-1] involves understanding indexing, negative indexing, and slicing. For a thorough explanation, consider this article.

Python iterables, such as lists and strings, support slicing.

Slicing is used to return a specific range of elements from an iterable. For example, you can slice a string to get the first n characters.

For instance, let’s grab the first 4 characters from a sentence:

string = "This is a test"
part = string[0:4:1]

print(part)

Output:

This

In this piece of code, string[0:4:1] means get a slice of the string that:

  • Starts from the first character (index 0).
  • Ends before the 5th character (index 4).
  • Takes steps of size 1, that is, returns every character from that range.

Generally, slicing thus follows this syntax:

iterable[start:end:stepsize]

However, if you start slicing from the very beginning of the iterable, you do not need to specify the start parameter.

For example, to grab the first 4 characters, you can do this:

string = "This is a test"
part = string[:4:1]

print(part)

Output:

This

The same applies when you stop at the very end of the iterable. You do not need to specify the stop parameter.

For example, to slice a string so that you get the whole string back:

string = "This is a test"
part = string[::1]

print(part)

Output:

This is a test

Last but not least, Python slicing also supports negative stepsize. This means the string is traversed backward.

For example, to get the whole string in reversed order:

string = "This is a test"
part = string[::-1]

print(part)

Output:

tset a si sihT

As the stepsize is -1, the slicing starts from the stop parameter and stops at the start parameter. But neither of those parameters is specified. Thus it automatically starts slicing from the last element and ends at the first one. In other words, it reverses the string.

4. List of Strings to a String

You can combine a list of strings using the built-in join() method to form a long string.

For instance:

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

print(combined)

Output:

This is a Test

Explanation

Python string type str has a built-in method join(). This method joins a sequence of strings using a separator string. In other words, you can use the join() method to combine a sequence of strings to make it one long string.

The join() method follows this syntax:

separator.join(iterable)

Where the separator string is added in-between each element in the iterable.

For example, let’s join a list of strings:

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

print(combined)

The result is a long string where white spaces separate each word in the list:

This is a Test

Notice how the sequence of strings you want to join does not have to be a list. It can be any iterable, such as a tuple:

words = ("This", "is", "a", "Test")
combined = " ".join(words)

print(combined)

Output:

This is a Test

In Python, a string is also an iterable type that consists of a sequence of characters.

This means you can also call join() with a string argument.

For example, let’s separate the characters of a string with a dash:

dashed = "-".join("Test")
print(dashed)

Output:

T-e-s-t

5. Mathematical Comparison Chains

In Python, you can combine comparisons instead of splitting the statement into two or more parts.

For instance:

x = 100
res = 1 < x < 200

print(res)

Output:

True

Explanation

In mathematics, you commonly deal with values that should be in a specific range.

For example, if you want a temperature T to be between 40 and 50 Fahrenheit, you can denote it by:

40 < T < 50

However, some programming languages do not allow chaining comparisons this way. Instead, they require you to split the expression into two parts:

  • T is less than 50
  • T is more than 40.

You can then combine these with the language-specific and operator.

In Python, it would mean an expression like this:

T > 40 and T < 50

The downside of this expression is it takes a second to understand that it actually means 40 < T < 50. Furthermore, it takes a second longer to write it and it also takes additional characters.

Luckily, in Python, chaining comparisons is possible. In other words, you can write:

40 < T < 50

This is useful to make mathematical code look more like actual maths.

6. Most Frequent Element in a List

In Python, it is possible to use a one-liner to find the most frequent element in a list.

For instance:

numbers = [6, 2, 2, 3, 4, 2, 2, 90, 2, 41]

most_frequent = max(set(numbers), key = numbers.count)

print(most_frequent)

Output:

2

Explanation

First of all, this is a poor “trick” to find the most frequent element in a list. But as it is a one-liner that only uses native code, it had to be included in the list.

A better approach for finding the most frequent element would be to use the statistics module.

For example:

import statistics
numbers = [6, 2, 2, 3, 4, 2, 2, 90, 2, 41]

most_frequent = statistics.mode(numbers)
print(most_frequent)

Output:

2

Anyway, let’s take a look at how the trick to finding the most frequent element really works.

First of all, you do not need to convert the list into a set. This piece of code would also get the job done:

max(numbers, key = numbers.count)

But how does it work?

When you call max() function in Python, by default it finds the largest element. However, sometimes this is not what you want. For instance, maybe you want to find the longest string in a list.

To change what is meant by maximum, specify a key parameter into the call. This key is a function that the max() function calls on each element before picking up the maximal element.

To find the most frequent element in the numbers list, the key is specified as numbers.count function.

This means numbers.count(n) is called on each number n in the numbers list. This produces a list of numbers that represent how many times each number occurs in the list. The max() function then picks up the item with the highest number of occurrences  based on that list.

But why did you convert the list into a set in the original version of the trick?

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

The list.count is an O(n) operation. Furthermore, it is performed on each element of the list. This means the trick is an O(n2) operation, which means pretty poor performance.

To improve the performance a bit, you can convert the list into a set.

This speeds up the process because a Python set does not have duplicate values. Thus, each number frequency is checked only once.

However, the operation is still an O(n2) operation, which means it performs poorly even with this slight improvement.

7. Exctract List to Variables

You can unpack list items to variables as long as the number of variables remains the same as the number of elements in the list.

For example:

arr = [1, 2, 3]
a, b, c = arr

print(a, b, c)

Output:

1 2 3

Explanation

The explanation for this “trick” is the same as the explanation for the trick of swapping two variables.

In Python, it is possible to unpack values from iterables into separate variables.

To do this, you need to have an equal number of variables on the right-hand side as there are values on the iterable on the left-hand side.

To see more details, feel free to jump back to the explanation of the first trick in this article.

8. One-Liner If-Else Statements

In Python, you can replace an if-else statement with a one-liner shorthand.

For example:

age = 30
age_group = "Adult" if age > 18 else "Child"

print(age_group)

Output:

Adult

Explanation

If you know some other programming languages, such as JavaScript or C, you may be familiar with a ternary operator. It can be used to replace an if-else statement with a question mark-colon statement like this:

condition ? true_expr : false_expr

Even though this is commonplace in many popular programming languages, Python does not support it as-is.

However, Python supports a conditional operator (sometimes also called a ternary operator). This is a very similar syntax that allows writing one-liner if-else statements.

Here is the syntax for using the conditional operator in Python:

true_expression if condition else false_expression

This can be handy if you have a simple if-else statement you want to make shorter.

For instance, normally you would do:

age = 30

if age < 18:
    age_group = "Child"
else:
    age_group = "Adult"

But by using the conditional operator, you can replace the if-else statement with a more concise shorthand:

age = 30
age_group = "Adult" if age > 18 else "Child"

However, keep in mind you should not sacrifice code readability for this. With that being said, it is completely fine to never use an expression like this.

But if you want to save some lines of code, please make sure to use the conditional operator only with simple if-else statements.

Here is a bad example of using a conditional operator in Python:

result = x * 2 + 10 if x % 2 == 0 else x / 2 - 10

As you can see, it is impossible to read this mess! But if you write it as a regular if-else, it instantly becomes evident what the code does:

if x % 2 == 0:
    result = x * 2 + 10
else:
    result = x / 2 - 10

Use conditional operators wisely!

9. One-Liner For Loops

In Python, it is possible to write for loops as one-liners.

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

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

print(squared_numbers)

Output:

[1, 4, 9, 16, 25]

Explanation

The one-liner for loop you saw above is called list comprehension. It is a shorthand for iterating through lists in Python.

A list comprehension operates on an existing list of values and produces a new one.

Generally, the list comprehension uses the following syntax:

newlist = [expression for item in iterable if condition]

Just like a regular for loop, the list comprehension:

  • Takes a list of items.
  • Performs an operation on each item (if a condition is met).
  • Puts the result in a new list.
  • Returns the new list.

For example, let’s square the even numbers of a list of numbers.

First, let’s use a regular for loop:

numbers = [1, 2, 3, 4, 5, 6, 7, 8]

squared_numbers = []
for number in numbers:
    if number % 2 == 0:
        squared_numbers.append(number ** 2)

print(squared_numbers)

Output:

[4, 16, 36, 64]

Then let’s compress the for loop into a one-liner with a list comprehension:

numbers = [1, 2, 3, 4, 5, 6, 7, 8]

squared_numbers = [n ** 2 for n in numbers if n % 2 == 0]

print(squared_numbers)

Output:

[4, 16, 36, 64]

This nicely makes the code shorter and preserves the readability. And by the way, it also is slightly faster than a regular for loop.

Similar to the one-liner if-else, do not overuse list comprehensions in Python! This can sacrifice the code readability. For example, it is possible to write nested for loops as nested list comprehensions, but it is rarely beneficial. Even though comprehension is slightly faster than a for loop, it is not worth using only for performance.

Remember, it is not wrong to never use a comprehension in Python.

Last but not least it is good to know that Python supports comprehensions for other iterable types too. In total, Python supports four different types of comprehensions:

  1. List comprehension
  2. Dictionary comprehension
  3. Set comprehension
  4. Generator comprehension (also known as Generator expression)

To learn more about these, please take a look at this article.

10. Simplify If Statement Comparisons

Instead of this rather verbose comparison mess:

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

You can do this:

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

Explanation

In Python, you can check if multiple conditions hold using the or operator.

However, if you are checking if a value is equal to one of many values, there is a better way to do it than chaining tons of or operations. Namely, put all the possible values into a list, and check if your target value is in the list.

To check if a value exists in a list in Python, use the in operator. It goes through an iterable and checks if the target value is found. This approach returns True if a value is found and False if not.

For instance:

10 in [1, 2, 3] # Returns False
1 in [1, 2, 3]  # Returns True

Conclusion

Today you learned a bunch of useful Python “tricks” you can impress your mates with. Instead of knowing them by heart, you also saw how each of the tricks works.

Anyway, I hope you found this article insightful. Thanks for reading.

Happy coding!

Further Reading

Python Interview Questions