Skip to content
Search
Generic filters
Exact matches only

30 Magical Python Tricks to Write Better Code

Python is quite a popular language among others for its simplicity and readability of the code. It is one of the simplest languages to choose as your first language. If you are a beginner with the basic concepts of python then this is the best time to learn to write better codes.

There are a lot of tricks in python that can improve your program better than before. This article will help you to know various tricks and tips available in python. Practice them continuously until it becomes a part of your programming habit.

Python allows us to assign values for more than one variable in a single line. The variables can be separated using commas. The one-liners for multiple assignments has lots of benefits. It can be used for assigning multiple values for multiple variables or multiple values for a single variable name. Let us take a problem statement in which we have to assign the values 50 and 60 to the variables a and b. The usual code will be like the following.

Output

Condition I – Values equal to Variables

When the variables and values of multiple assignments are equal, each value will be stored in all the variables.

Output

Both the programs gives the same results. This is the benefit of using one line value assignments.

Condition II – Values greater than Variables

Let us try to increase the number of values in the previous program. The multiple values can be assigned to a single variable. While assigning more than one value to a variable we must use an asterisk before the variable name.

Output

The first value will be assigned to the first variable. The second variable will take a collection of values from the given values. This will create a list type object.

Condition III – One Value to Multiple Variables

We can assign a value to more than one variable. Each variable will be separated using an equal to symbol.

Output

Swapping is the process of exchanging the values of two variables with each other. This can be useful in many operations in computer science. Here, I have written two major methods used by the programmer to swap the values as well as the optimal solution.

Method I – Using a temporary variable

This method uses a temporary variable to store some data. The following code is written with temporary variable name.

Output

Method II – Without using a temporary variable

The following code swaps the variable without using a temporary variable.

Output

Method III – Optimal Solution in Python

This is a different approach to swap variables using python. In the previous section, we have learned about multiple assignments. We can use the concept of swapping.

Output

There is an another cool trick for reversing a string in python. The concept used for reversing a string is called string slicing. Any string can be reversed using the symbol [::-1] after the variable name.

Output

No special algorithm is required for splitting the words in a line. We can use the keyword for this purpose. Here I have written two methods for splitting the words.

Method I – Using iterations

Output

Method II – Using split function

Output

This is the opposite process of the previous one. In this part we are going to convert a list of words into a single line using join function. The syntax for using join function is given below.

Syntax: “ ”.join(string)

Output

We can use the multiplication operator to print a string for multiple times. This is a very effective way to repeat a string.

Output

Joining various strings can be done without using the join function. We can just use the addition operator (+) to do this.

Output

Two combine two or more conditional operators in a program we can use the logical operators. But the same result can be obtained by chaining the operators. For example, if we need to do print something when a variable has the value greater than 10 and less than 20, the code will be something like the following.

Instead of this we can combine the conditional operator into single expression.

Output

Learn more about operators in the following article.

The element which occurs most of the time in a list then it will be the most frequent element in the list. The following snippet will help you to get the most frequent element from a list.

Output

The previous code will give the most frequent value. If we need to know the occurrence of all the unique element in a list, then we can go for the collection module. The collections is a wonderful module in python which gives great features. The method gives a dictionary with the element and occurrence pair.

Output

Two strings are anagrams if one string is made up of the characters in the other string. We can use the same Counter method from the collections module.

Output

The function range() is useful for creating a sequence of numbers. It can be useful in many code snippets. The syntax for a range function is written here.

Syntax: range(start, end, step)

Let us try to create a list of even numbers.

Output

Similar to the string multiplication we can create a list filled with an element multiple times using multiplication operator.

Output

In most of the time, we use nested conditional structures in Python. Instead of using nested structure, a single line can be replaced with the help of ternary operator. The syntax is given below.

Syntax: Statement1 if True else Statement2

age = 25
print(“Eligible”) if age>20 else print(“Not Eligible”)

Output

List comprehension is a very compact way to create a list from another list. Look at the following codes. The first one is written using simple iteration and the second one is created using list comprehension.

Output

Using List Comprehension

Output

The function frozenset() is used to convert mutable iterable into immutable object. Using this we can freeze an object from changing its value.

Output

As we applied the frozenset() function on the list, the item assignment is restricted.

Floor and Ceil are mathematical functions can be used on floating numbers. The floor function returns an integer smaller than the floating value whereas the ceil function returns the integer greater than the floating value. To use this functions we have to import math module.

Output

Some times we have to return a boolean value by checking conditions of certain parameters. Instead of writing if else statements we can directly return the condition. The following programs will produce the same output.

Method I – Using If Else Condition

Method II – Without If Else Condition

Output

Lambda is an anonymous function in python that creates function in one line. The syntax for using a lambda function is given here.

Syntax: lambda arguments: expression

Output

Map is a higher order function that applies a particular function for all the elements in list.

Syntax: map(function, iterable)

Output

The function can be replaced by a lambda function in python. The following program is created for creating square of list of numbers.

Output

Learn more about higher order functions here.

A python function can return more than one value without any extra need. We can just return the values by separating them by commas.

Output

Filter function is used for filtering some values from a iterable object. The syntax for filter function is given below.

Syntax: filter(function, iterable)

Output

In python, we can merge two dictionaries without any specific method. Below code is an example for merging two dictionaries.

Output

The memory size varies based on the type of object. We can get the memory of an object using getsizeof() function from the sys module.

Output

The zip unction has many advantages in python. Using zip function we can create a dictionary from two lists.

Output

Time is another useful module in python can be used to calculate the execution time.

Output

An element that occurs more than one time is called duplicate element. We can remove the duplicate elements simply using typecasting.

Output

Calendar module has many function related to the date based operations. We can print monthly calendar using the following code.

Output

The zip functions enables the process of iterating more than one iterable using loops. In the below code two lists are getting iterated simultaneously.

Output

I hope you enjoyed this article. As an end note, you have to understand that learning the tricks is not a must. But if you do so, you can stand unique among other programmers. Continuous practice is must to become fluent in coding. Thank you for reading this article. You can follow me on medium.

Happy Coding!