30 Essential Python Tips and Tricks for Programmers

If you ask any Python programmer to tell about the strengths of Python, he will quote brevity and high readability as the most influencing ones. In this Python tutorial, we’ll cover many essential Python tips and tricks that will authenticate the above two points.

We’ve been collecting these useful shortcuts (tips & tricks) since we started using Python. And what’s best than sharing something we know and which could benefit others as well.

In the past, we’d shared a list of Python programming tips for beginners that aimed to optimize code and reduce coding efforts. And our readers still enjoy reading it.

So today, we’re back with one more set of essential Python tips and tricks. All these tips can help you minify the code and optimize execution. Moreover, you can readily use them in live projects while working on assignments.

Each trick has an example given with a brief explanation. For testing the coding snippets, you can look up these online virtual terminals for Python code execution.

There are two more key Python resources that we’d recently published which you must look at are as follows.

30 Essential Python Tips and Tricks for Programmers.

Tips#1. In-place swapping of two numbers.

Python provides an intuitive way to do assignments and swapping in one line. Please refer the below example.

The assignment on the right seeds a new tuple. While the left one instantly unpacks that (unreferenced) tuple to the names <a> and <b>.

Once the assignment is through, the new tuple gets unreferenced and flagged for garbage collection. The swapping of variables also occurs at eventually.


Tips#2. Chaining of comparison operators.

Aggregation of comparison operators is another trick that can come handy at times.


Tips#3. Using Ternary operator for Conditional assignment.

Ternary operators are a shortcut for an if-else statement and also known as conditional operators.

Here are a few examples which you can use to make your code compact and concise.

The below statement is doing the same what it is meant to i.e. “assign 10 to x if y is 9, otherwise assign 20 to x“. We can though extend the chaining of operators if required.

Likewise, we can do the same for class objects.

In the above example, classA and classB are two classes and one of the class constructors would get called.

Below is one more example with a no. of conditions joining to evaluate the smallest number.

We can even use a ternary operator with the list comprehension.


Tips#4. Multi-line strings.

The basic approach is to use backslashes which derive itself from C language.

One more trick is to use the triple-quotes.

The common issue with the above methods is the lack of proper indentation. If we try to indent, it’ll insert whitespaces in the string.

So the final solution is to split the string into multi lines and enclose the entire string in parenthesis.


Tips#5. Storing elements of a list into new variables.

We can use a list to initialize a no. of variables. While unpacking the list, the count of variables shouldn’t exceed the no. of elements in the list.


Tips#6. Printing the file path of imported modules.

If you want to know the absolute location of modules imported in your code, then use the below trick.


Tips#7. Interactive “_”.

It’s a useful feature which not many of us are aware.

In the Python console, whenever we test an expression or call a function, the result dispatches to a temporary name, _ (an underscore).

The “_” references to the output of the last executed expression.


Tips#8. Dictionary/Set comprehensions.

Like we use list comprehensions, we can also use dictionary/set comprehensions. They are simple to use and just as effective. Here is an example.

Note- There is only a difference of <:> in the two statements. Also, to run the above code in Python3, replace <xrange> with <range>.


Tips#9. Debugging scripts.

We can set breakpoints in our Python script with the help of the <pdb> module. Please follow the below example.

We can specify <pdb.set_trace()> anywhere in the script and set a breakpoint there. It’s extremely convenient.


Tips#10. Setup file sharing.

Python allows running an HTTP server which you can use to share files from the server root directory. Below are the commands to start the server.

# Python 2

# Python 3

Above commands would start a server on the default port i.e. 8000. You can also use a custom port by passing it as the last argument to the above commands.


Tips#11. Inspect an object in Python.

We can inspect objects in Python by calling the dir() method. Here is a simple example.


Tips#12. Simplify if statement.

To verify multiple values, we can do in the following manner.

instead of:

Alternatively, we can use ‘{1,3,5,7}’ instead of ‘[1,3,5,7]’ for ‘in’ operator because ‘set’ can access each element by O(1).


Tips#13. Detect Python version at runtime.

Sometimes we may not want to execute our program if the Python engine currently running is less than the supported version. To achieve this, you can use the below coding snippet. It also prints the currently used Python version in a readable format.

Alternatively, you can use sys.version_info >= (3, 5) to replace sys.hexversion != 50660080 in the above code. It was a suggestion from one of the informed reader.

Output when running on Python 2.7.

Output when running on Python 3.5.


Tips#14. Combining multiple strings.

If you want to concatenate all the tokens available in a list, then see the below example.

Now, let’s create a single string from the elements in the list given above.


Tips#15. Versatile reverse mechanism.

# Reverse the list itself.

# Reverse while iterating in a loop.

# Reverse a string in line.

This gives the output as ”nohtyP tseT”

# Reverse a list using slicing.

The above command will give the output as [5, 3, 1].


Tips#16. Play with enumeration.

With enumerators, it’s easy to find an index while you’re inside a loop.


Tips#17. Using enums in Python.

We can use the following approach to create enum definitions.


Tips#18. Returning multiple values from functions.

Not many programming languages support this feature. However, functions in Python do return multiple values.

Please refer the below example to see it working.


Tips#19. Unpack function arguments using splat operator.

The splat operator offers an artistic way to unpack arguments lists. Please refer the below example for clarity.


Tips#20. Use a dictionary to store a switch.

We can make a dictionary store expressions.


Tips#21. Calculate the factorial of any number in one line.

Python 2.x.

Python 3.x.


Tips#22. Find the most frequent element in a list.


Tips#23. Resetting the recursion limit.

Python restricts recursion limit to 1000. We can though reset its value.

Please apply the above trick only if you need it.


Tips#24. Check the memory usage of an object.

In Python 2.7, a 32-bit integer consumes 24-bytes whereas it utilizes 28-bytes in Python 3.5. To verify the memory usage, we can call the <getsizeof> method.

In Python 2.7.

In Python 3.5.


Tips#25. Use __slots__ to reduce memory overheads.

Have you ever observed your Python application consuming a lot of resources especially memory? Here is one trick which uses <__slots__> class variable to reduce memory overhead to some extent.

Clearly, you can see from the results that there are savings in memory usage. But you should use __slots__ when the memory overhead of a class is unnecessarily large. Do it only after profiling the application. Otherwise, you’ll make the code difficult to change and with no real benefit.


Tips#26. Using lambda to handle printing.


Tips#27. Create dictionary from two related sequences.


Tips#28. In line search for multiple prefixes in a string.


Tips#29. Form a unified list without using any loops.


Tips#30. Implementing a true switch-case statement in Python.

Here is the code that uses a dictionary to imitate a switch-case construct.


Summary – Essential Python Tips and Tricks for Programmers.

We wish the essential Python tips and tricks given above would help you do the tasks quickly & efficiently. And you could use them for your assignments and projects.

Listening to your feedback makes us do better so share it.

You can even ask us to write on a topic of your choice. We’ll add it to our writing roadmap.

Lastly, if you’d enjoyed the post, then please care to share it with friends and on social media.

Keep Learning,



  1. Just-A-Programmer Reply
  2. Luiz Felipe do Divino Reply
  3. Mark B Reply
  4. suresh Reply
  5. Pramod Reply
  6. Anon Reply

Leave a Reply