10 Useful Python Tips and Tricks✨

10 Useful Python Tips and Tricks✨

Hey guys👋 Welcome back to my blog! Python is quite popular nowadays, mainly due to its easiness to learn. Moreover, it can be used for a wide range of tasks like data science, machine learning, game development, web scraping, etc.

Today, I'm gonna share some tips and tricks to make programming in python much easier than it already is😉

So, without any further ado, let's get started!

1. Dividing large numbers in chunks

Let's talk with practicality. Take a look at the numbers below and tell me, which number would you be able to understand and say faster?

• 7683423898

• 1,989,738,100

Obviously, you guys are gonna answer that the second one is easier to understand. Why is that? That's because it is divided into thirds. Everybody understands basic maths and knows that the fourth part is the billions. Therefore the number is one billion, nine hundred eighty-nine million, seven hundred thirty-eight thousand, one hundred. This division makes it much faster to understand which part is the billions and which is the millions etc.

In Python, you can place underscores in numbers so you can use them to divide up any large number. This will help improve the readability of the data entered as well as the code.

** Example:**

a = 122_343_090
print(a*2 + 32_400)

# or

b = (4_2_8_9) # Only a psychopath is gonna do this🙄

2. The Walrus(:=) Operator

This is one of the latest additions to Python. The walrus operator was added to Python in version 3.8. It is basically an assignment expression that allows assignment directly in the expression.

Usual way:

a = [1,2,3]
b=len(a)
if b > 2:
      print(b)

In the above-mentioned example, we declared a list. Then we declared a variable ‘b’ to assign the value of the length of the list.

But by using the walrus operator:

a = [1,2,3]
if (b := len(a) > 2):
      print(b)

Here, we declared and assigned the value at the same time. This method helps to decrease the lines of code too.

3. Reading passwords

This method will give users a good experience in simple menu-based applications as well. The getpass module will be used to read in passwords from the users in the console applications.

Example:

from getpass import getpass

username = input("username: ")
password = getpass("password : ")

Output:

username: Ayesha145
password: *******

This method hides the user input for the password field on the console. You can use this method while making any management system project (the professors just love to assign such projects☹) to make the user experience better. Cool trick, isn't it?

4. Lambda Function

Lambda functions are also called anonymous functions as they don’t have names. They are used a lot in fields like Data Science, ML, Backend using Django, and many more. Let’s check an example to add two numbers.

Simple Function:

def add(a,b):
          return a + b

add(1,8)

**Lambda function: **

add = lambda a,b : a+b
add(1,8)

Lambda functions are often useful to allow quick calculations or processing as the input to other functions. They make code easier to read if they're used appropriately.

5. Replacing nested ifs with if/continue

Consider the following example: we want to loop through each element in a 3 by 3 matrix, which is done with two "for loops". If the element satisfies a certain condition, we’ll perform some action with or on the numbers. Although this example is way too basic, writing an if statement in this manner makes your code a lot less readable.

This is especially the case if there are already many indents before and after so it’s safe to say that it is almost always better to reduce the amount of necessary indentation in our code. If there is only a need to include an if statement but not an elif or else component, we can write the code another way. If the condition is not true, we call the continue keyword, which will skip anything left in the iteration and then continues to the next. This method is very helpful in making complex code more readable!!!

6. Simplify an "if statement"

Sometimes you have to verify multiple values. What's the method you use? This one seems legit, right?

if a == 1 or a == 3 or a == 5 or a == 7:

Guess what, you can also do it like this:

if a in [1,3,5,7]:

This method makes it much easier to understand the condition, resulting in a readable code.

7. Printing the file path of imported modules

We always use modules such as os, pygame etc. Ever thought about where they come from? If you did then here's how to find out!

import os
import pygame

print(os)
print(pygame)

Output:

<module 'os' from 'C:\\Users\\Dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\os.py'>
<module 'pygame' from 'C:\\Users\\Dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\pygame\\__init__.py'>

8. Assigning multiple variables in 1 line

Sometimes, assigning a lot of variables takes up a lot of lines and all you want to do is make your code smaller. So here's how to assign variables in just 1 line, yes, you heard me right :)

a, b, c = 1, 2, 3

It's as simple as that!

9. Removing duplicates from a list

Lists can have duplicate elements and let's admit it people, even though it is useful but sometimes duplicates prove to be unwanted. I got a solution for you guys!

Num = [10, 12, 14, 16, 18, 18, 10, 10, 14]
print("Original list: ", Num) 
Num = list(set(Num))
print("After removing duplicates: ", Num)

Output:

Original list: [10, 12, 14, 16, 18, 18, 10, 10, 14]
After removing duplicates: [10, 12, 14, 16, 18]

Easy, isn't it? Just convert a list into a set and then change it back, all in 1 line! Changing it in a set removes all duplicates because sets don't have duplicates.

10. Printing values with a custom separator

Chances are that you haven't seen this trick before. Well in my case, till now I didn't have to use a custom separator so never got to know this one. But fret not my friends, it's quite easy.

print("05", "09", "2021", sep="/")  
print("username", "gmail.com", sep="@")

Output:

05/09/2021
username@gmail.com

Conclusion

All these tricks might seem very simple but believe me, if you use them, it will definitely make your life much easier and your code much more readable! Let me know in the comments below about any cool trick that you guys know about. I would definitely try them out. Moreover, I would love to know if you guys found this article helpful :)