7 Python Tips For Better Code

In this post, I will share 10 tips to help you write better, more readable code in Python, some of which you are likely to know, some of which are more rarely used features and suggestions.


A feature doesn’t use by most beginner Python programmers, f strings allow you to specify your variables in strings. logically similar to the formatting method.

num1 = 122
str2 = "Command"

print(f"Call the {num1}th {str2}")
Output: Call the 122th Command

Find the Size of Any Object

With the help of the function called getsizeof, you can see how much space the objects occupy in bytes. You have to call the sys module to access this function.

import sys

x = {"X": 123 , "Y": 21 , "Z": 42}
y = 1

size = sys.getsizeof(x)
size2 = sys.getsizeof(y)

print(size , "byte" , size2 , "byte")
232 byte

Enumerate Functions

When iterating over an object such as a list, dictionary, or file, enumerate is a useful function. The function returns a tuple containing both the values obtained from iterating over the object and the loop counter. The loop counter is especially handy when you want to write code based on the index.

def Enum(lst , length):

for i, element in enumerate(lst):
   print('{}: {}'.format(i, element))
   if i == length - 1:
      print('The last element!')

lst = 'Index'
length = len(lst)

Enum(lst , length)
0: I
1: n
2: d
3: e
4: x
The last element!

Big Number Readability

This tip, which can be useful for people working with large numbers, increases the readability of large numbers.

num1 = 100_000_000_000
numBasic = 100000000000

You have understood the difference, it is useful for improving readability. Likewise, it can be used in float variables.

Chain Operators

This operator will help you find the number range of a variable, which will often come in handy in comparison expressions.

num = 99
control = 50 < num < 100

Output: True

Merging Strings

you can combine the data that needs to be combined with the join function. The join function returns a string.

lst = ["Usa" , "South Korea" , "China" , "Japan"]
str= " ".join(lst)

Output: Usa South Korea China Japan

Break Up Strings

It is possible to divide strings into indexes by dividing them. For this, a split function should be used. After the specified character, the string is split and added to the list.

str = "Example Example2 Example3"
a = str.split(" ")

print (a)
Output: ['Example', 'Example2', 'Example3']

Leave a Reply

Your email address will not be published. Required fields are marked *