Python Tips And Tricks

Python Tips And Tricks

There are many tips and tricks in Python that can make your coding a bit easier. In this tutorial, we’re going to take a look at a whole bunch of tips and tricks you might like when working with Python. Some of the topics to cover include the Python conditional operator (Ternary), merging dictionaries, underscores to help with large numbers, printing a list in a specific order, how to use context managers, finding the most common item in a list, using the enumerate function, swapping variables, using help(), using zip(), and many more.


Python Ternary Operator

The first tip to look at is the ternary operator in Python. It is also sometimes called the ternary conditional. The ternary was added to the 2.5 version of Python. The Python ternary is useful in some situations to help shorten your code or make it more clear. So how is it used? First, let’s look at a simply if/else conditional in Python. It is a common pattern where you check to see if a condition is True or False, and then assign a value to a variable based on the result of that condition.

myvariable is 1

Since the condition is true, the variable gets set to 1. Let’s set the condition to False now to see how the variable then gets set to 0.

myvariable is 0

The Ternary

A faster way to write this is by using the Ternary Conditional in Python. This effectively turns the if/else construct into a simple one-liner. In the code below, we can see how this works. Just because it is now a one-liner does not mean it is better. The goal is to write code you and others can understand in an easy way. Many times the ternary conditional is just as easy to read, especially once you are used to it. So if it makes the code shorter, then that is an added bonus.

othervariable is 1

othervariable is 2

Merge Two Dictionaries

The next trick is how to merge two Python dictionaries into one variable. This can be done with the double asterisk ** operator introduced in Python 3.5. Each item is added to the new dictionary and overlapping entries use the value of the later item. Here it is in action.

{'a': 1, 'b': 2, 'c': 4, 'd': 5, 'e': 6}

Underscores As Commas In Large Numbers

This tip deals with when you are working with large numbers in Python. In Python, you can’t use commas to break up big numbers. So instead of writing a number like 70,000,000,000, you have to write it as 70000000000. Looking at a number like that is easy to mistake the size of the number. The trick you can use is to put underscores in place of where the commas would go, and Python allows that.

70070000000

Math still happens correctly. Then you can use an F string in Python to add commas like so to the output.

70,070,000,000

Specify Print Order of a List

This neat little trick in Python allows you to print a list in any order you choose.

10 20 30 40
40 20 30 10

Leveraging Python Context Managers

When reading and writing files in Python, there are a few ways to complete that task. Consider this file and the following code.

python file on disk

12

The code above first manually opens a file, then reads the file, then the file is manually closed. Once we have the contents of the file, we then split the words using spaces as the delimiter, count the words and print them out. When you need to manually manage resources like opening and closing the file as seen here, it is a clue that there might be a better way to go about it. The better way to do this is by the use of a Context Manager. The purpose of the context manager is to manage resources for you, so you don’t need to deal with it manually. Here is the code that was rewritten using the with context manager, and I think you’ll agree it is a nice result.

12

Find Most Common Item In A List

This Python trick shows you how to find the most common item in a list. The example below has a list of strings. Specifically, there are a bunch of vegetables in a list, and we want to find the vegetable that we have the most of. Here is how to do that.

broccoli

If there is a tie, the item that reaches the higher count first wins.

beans

Enumerate Function In Python

The next Python tip concerns learning how to use the enumerate() function in Python. In other languages when you use a for loop to iterate, you automatically get access to an index so you can keep track of where you are in the loop. Python doesn’t really have that so sometimes you’ll see code like this to manually create an index.

1 Broccoli
2 Brussels Sprouts
3 Cauliflower
4 Butternut Squash

A better approach is to use enumerate() since it was designed for this type of application. By default, when you use enumerate(), the index begins at 0. We can change the starting point however by making use of the start parameter and setting it to 1.

1 Broccoli
2 Brussels Sprouts
3 Cauliflower
4 Butternut Squash

Swap Two Variables

A cool trick you can do in Python is to easily swap variables. Let’s see how this works. First, we have two variables with some data and print them out getting what we would expect.

Tom Jerry

To reverse what each variable holds, all we have to do is swap the order like so. No need to set up temporary variables.

Jerry Tom

The above snippet deals with simple strings, integers work the same as well.

10 20
20 10

Looping Over Multiple Lists At Once

Sometimes you might want to loop over more than one list at a time in Python. This tip will help you to do this type of thing. Let’s say you have two lists. Your goal is to access the first value of both lists on the first iteration, then access the second value of both lists on the second iteration, and so on. There are a few ways to do this. The first is by using the enumerate() function that we just learned about.

Broccoli topped with Cheese
Brussels Sprouts topped with Garlic
Cauliflower topped with Olive Oil
Butternut Squash topped with Butter

So we can see the purpose of looping over two lists at once. Each index of each list is somehow related to the corresponding index of another list. Perhaps a cleaner way to accomplish this is by using the zip() function in Python. Let’s see how that works.

Broccoli topped with Cheese
Brussels Sprouts topped with Garlic
Cauliflower topped with Olive Oil
Butternut Squash topped with Butter

Pretty cool! Why stop at two lists though? Let’s easily loop over three lists at a time!

Fried Broccoli topped with Cheese
Baked Brussels Sprouts topped with Garlic
Steamed Cauliflower topped with Olive Oil
Baked Butternut Squash topped with Butter

Adding An Emoji In Python

This list of tricks in Python would not be complete without seeing how to add an Emoji to your Python code. How is it done? First, you need to install the package with pip install emoji, then we can use code like this.

Python is 🔥

Unpacking Values in Python

Unpacking allows you to assign many values at one time. It is very convenient and allows you to express a lot of logic in terse syntax. Let’s see a few examples of Unpacking values in Python. The following code unpacks two values from a tuple and places them each in their own variable. You can do this with as many values as you like.

1
2

To unpack values but ignore a particular value, you can use an underscore as a placeholder like so.

1

Typically you want to have the same number of variables on the left of the = as to the number of values you are trying to unpack on the right of the =. The mapping should be equal. There is a bit of way around this by using the * operator. Using this approach, you can unpack say the first two values to their own variables, and then take the rest of the values and assign them to a list.

1
2
[3, 4, 5]

The same underscore trick can be used to ignore certain values as we saw above.

1
2

Here is another example of this trick.

1
2
[3, 4]
5

Capitalize Each Word In A Sentence

There are a load of tricks you can do on strings, but one of my favorites is simply applying the title() method to a string to capitalize the first letter of each word in a string. For example:

Python Tips And Tricks

Using Help()

Imagine your internet just went down and you have no access to the Python documentation. You have some questions about the function or module you are trying to use. Fear not! The help() module is your friend. In fact for our first trick, we will use help() on help. Observe:

Help on _Helper in module site object:

class _Helper(builtins.object)
 |  Define the built-in 'help'.
 |  This is a wrapper around pydoc.help (with a twist).
 |  
 |  Methods defined here:
 |  
 |  __call__(self, *args, **kwds)
 |      Call self as a function.
 |  
 |  __repr__(self)
 |      Return repr(self).
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

Three fantastic functions exist to help you navigate your way through Python code when building and debugging. These are type(), id(), and dir(). What do they do? Let’s see what help() says.

Help on class type in module builtins:

class type(object)
 |  type(object_or_name, bases, dict)
 |  type(object) -> the object's type
 |  type(name, bases, dict) -> a new type
 |  
 |  Methods defined here:
 |  
 |  __call__(self, /, *args, **kwargs)
 |      Call self as a function.
 |  
 |  __delattr__(self, name, /)
 |      Implement delattr(self, name).
 |  
 |  __dir__(self, /)
 |      Specialized __dir__ implementation for types.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __instancecheck__(self, instance, /)
 |      Check if an object is an instance.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __setattr__(self, name, value, /)
 |      Implement setattr(self, name, value).
 |  
 |  __sizeof__(self, /)
 |      Return memory consumption of the type object.
 |  
 |  __subclasscheck__(self, subclass, /)
 |      Check if a class is a subclass.
 |  
 |  __subclasses__(self, /)
 |      Return a list of immediate subclasses.
 |  
 |  mro(self, /)
 |      Return a type's method resolution order.
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  __prepare__(...)
 |      __prepare__() -> dict
 |      used to create the namespace for the class statement
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs)
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __abstractmethods__
 |  
 |  __dict__
 |  
 |  __text_signature__
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __base__ = <class 'object'>
 |      The base class of the class hierarchy.
 |      
 |      When called, it accepts no arguments and returns a new featureless
 |      instance that has no instance attributes and cannot be given any.
 |  
 |  __bases__ = (<class 'object'>,)
 |  
 |  __basicsize__ = 440
 |  
 |  __dictoffset__ = 132
 |  
 |  __flags__ = 2148291584
 |  
 |  __itemsize__ = 20
 |  
 |  __mro__ = (<class 'type'>, <class 'object'>)
 |  
 |  __weakrefoffset__ = 184

Help on built-in function id in module builtins:

id(obj, /)
    Return the identity of an object.
    
    This is guaranteed to be unique among simultaneously existing objects.
    (CPython uses the object's memory address.)

Help on built-in function dir in module builtins:

dir(...)
    dir([object]) -> list of strings
    
    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.

Using pass

You might have seen some Python code where there is a function or class defined, but the only thing it has is a pass in it. What the heck is this? In Python, the pass keyword can be used to indicate that nothing happens. It is used in a function, class, or loop where you just want to stub out the code. Pass is used to quickly add things that are implemented. Below is a Veggie() class that does absolutely nothing.


Getting / Setting Object Attributes

Python class object are interesting in that you can dynamically add attributes and values to an object. Let’s see how this works.

Broccoli is Green

Interesting! The color and name attributes are not defined in any way inside of the class, we simply will them into being by using them.

We can set another attribute using the value of another variable if we want to. This is done using setattr() like so.

Spring

To get the attribute by the value of a variable, we can use getattr().

Spring

These two functions are useful when you are looping over some values where they are attributes that you want to access from an object. Let’s see what that means in code. Consider this dictionary that has some keys and values.

Let’s say I want to loop over the items in this dictionary and add them as attributes to the veggie object. With the code below, we loop over the dictionary, and each key becomes an attribute with each value getting assigned to that attribute on the object. This would be difficult to do without the setattr() function.

Butternut Squash is Orange

We can go in the other direction using getattr().

Orange
Butternut Squash

Checking For Substrings

Checking for the existence of a string inside of another string is one of the most common things you’ll do in your programs. This is easy to do in Python using in and not in.

In the string!

This is case sensitive as you can see.

Not in the string...

The not in operator works like so:

Eggs are not in the string

Secure Input

Most tutorials in Python will have you using some form of input to get data from the user. I’m sure you have seen code that looks similar to this.

password in clear text
The problem with this is your nosey co-worker might be looking over your shoulder and you just shared the password you use for the company network, Facebook, Twitter, your personal email, Tik Tok, and your dating profile. Not good. The solution is to use getpass()!

python tip use getpass

Now your password is obfuscated and no one, especially your nosey co-worker, can see it!


Use Pycharm

Having a nice IDE or integrated development environment will help you write better Python. Pycharm is one of the most powerful tools for writing Python and will help you with code hints, code formatting, debugging, refactoring, and much more. The professional version is a paid tool, however, the community edition is free and is almost as powerful.


Use Visual Studio Code

Pycharm is not your thing? No worries, you can use Visual Studio Code and make use of the many extensions that provide excellent Python support. Visual Studio Code is 100% free and a great tool for Python.


Use Jupyter Notebook

Jupyter Notebook is another great environment to get your feet wet with Python. You can use it to test simple snippets of Python code or make scientific presentations using something like matplotlib. Follow our guide on how to install Jupyter for more information.


Check if a list is empty in Python

You can check to see if a list is empty a few ways in Python. Here are some examples.

That list is empty

Empty List!

Empty List!

Sort A Dictionary By Value

To sort a dictionary by value you can use a lambda function in Python. Note, this approach leaves the orginal dictionary intact. We can assign the sorted result to a new variable and inspect it however.

{'the': 1, 'dictionary': 2, 'in': 3, 'so': 4, 'key': 5, 'fun': 6, 'random': 7}
{'random': 7, 'key': 5, 'in': 3, 'the': 1, 'dictionary': 2, 'so': 4, 'fun': 6}

Flatten A List of Lists

If you have several lists stored in a variable, you can flatten those into one list like so.

[[1, 2, 'three'], ['four', 5, 6], [7, 'eight', 9]]
[1, 2, 'three', 'four', 5, 6, 7, 'eight', 9]

What is if __name__ == “__main__”: for?

You see this line of code all the time in Python. So what does it do? Well here is an example Python file that copies a text file to another text file. Note the use of if __name__ == ‘__main__’:

Whenever the Python interpreter reads a source file it sets a few special variables like __name__, and then it executes all of the code found in the file. Every module in Python has a special attribute called __name__. The value of __name__ attribute is set to ‘__main__’ when the module is run as the main program.
Otherwise, the value of __name__ is set to contain the name of the module.

This behavior impacts running code from modules in Python. If you run a Python file directly, the __name__ variable is set to __main__. If however you import a Python file rather than run it directly, that file’s __name__ variable gets set to the name of the file. This is its module name at that point. Runs the main() function if the file was not imported.


Reverse A String

This little Python trick takes a string and perfectly reverses it.

dlrow eht elur ot stnaw ydobyrevE

Make A String From A List

The join() function in Python can take a list and make a string out of the items like so.

Welcome to your life

Print The Path Of A Module

To print the path of an imported module, simply pass the name of the module to the print() function.

<module 'requests' from 'C:\\python\\vrequests\\lib\\site-packages\\requests\\__init__.py'>

Print Memory Use Of A Variable

The .getsizeof() function will output the memory usage of a particular variable or object. Note the small string uses less memory and the larger string uses more memory in this example.

40
170

Chained Variable Assignment

You can create multiple variables that all reference the same object by way of chained assignment in Python.

Python Python Python Python

Comparisons can be chained

You can chain comparisons together to make a single Python expression.

Chained comparison in action

You can do this with more than one variable at a time, but things do start to get a little confusing so be careful with this one.

Chained comparison in action

Getting A Value From A Dictionary

This Python trick deals with getting a value from a dictionary. If we have a dictionary of prices, and we only want the price of one object but we’re not sure if that object is in the dictionary, how do we account for that? You need to check before using that value like so.

A better way to do this is to use the .get() method.

The coffee costs 3.50

The second approach reduces 4 lines of code down to 1 and sets a default value for the Coffee if it does not exist in the dictionary.


Using Else With For Loops

In Python you can use an else statement in combination with a for loop. To see how this trick works, first we look at the code we will want to improve by this tip.

Found it!

The better way to accomplish this is to use a for/else as we see here:

Found it!

Using Else With A Try/Except Block

Python has a cool trick that lets you use an else with a try/except block. First, we see the code that we’ll improve with this trick.

You can not divde by zero

What if we were to divide by 5 and still make use of the result? For that, use a simple else like so:

5.0

Renumber All Cells From Top To Bottom In Jupyter Notebook

If you have many cells in your Jupyter notebook, and during the process of adding cells you placed them above or below existing cells, you are going to have the cells numbered from top to bottom in an out of order fashion. If you would like to renumber the cells from top to bottom in Jupyter, you can select Kernel->Restart & Run All.

jupyter kernel restart and run all


Check Two Lists For Matches

If you have two lists of data and would like to see which items exist in both lists, you can use this trick.

{'BAC', 'AMRN', 'SQ', 'M', 'MU', 'MGM', 'BA', 'UBER', 'TSLA', 'LK', 'AAPL', 'TLRY', 'OXY', 'JPM'}

Python Print Without Newline

The print() function in Python automatically adds a newline on each call. Therefore if you use print() in a loop, you will end up with lots of newline characters. To stop this behavior, you can use this code.


Fly Using Python

Python is a magical language. In fact, you can fly with just one line of code.

Run the Python file that you put this snippet of code in and watch what happens 😃

python import antigravity


Learn The Zen of Python

Another one-liner trick in Python is to learn the Zen of Python. How do you do it? Like so:

The Zen Of Python


Using map() Function on Iterables

['R', 'G', 'B']

Two Argument Lambda Functions

Expanding on the prior example, multiple arguments can be passed to the lambda so that the function operates on any arbitrary number of iterables.

['10 Peppers', '20 Tomatos', '30 Leeks']

Python Tips And Tricks Summary

If you made it through all of these tips and tricks for the Python programming language, then you likely have an attention span forged with steel, congratulations! Have fun programming in Python 👍