Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

code optimization in python

HOW TO WRITE BETTER CODE IN PYTHON | TIP #1

1 - List comprehension
#DONT DO THIS:

list = []
for i in range(number):
    list.append(i)
    
#DO THIS:

list = [i for i in range(number)]
Comment

python code optimization

Here is a good optimization trick for many:


#INSTEAD OF:
list = []
for i in range(number):
    list.append(value)
 
#USE:
list = [value for i in range(number]


#INSTEAD OF:
for i in range(len(list)):
    #Do something
   
USE:
for i, value in enumerate(list):
    #Do something
    
    
APPLYING IT:

#THIS:
matrix = [[0 for i in range(number1)] for j in range(number2)]

#IS BETTER THAN:
matrix = []
for i in range(number1):
    row = []
    for j in range(number2):
        row.append(0)
    matrix.append(row)
Comment

optimization in python

OPTIMIZATION FOR PYTHON: TIP 2 - 4

2 - When importing modules you can import them all in a single line:

import module_1, module_2, module_3, etc...


3 - When importing everything from a module use *:

from random import *

We imported everything from the 'random' module using *, now we dont need to use 'random.'
FUN FACT: Not using module. increases performance since module. uses the get_attr function which
decreases performance


4 - When importing only a few things from a module combine the two tips above:

from random import randint, choice

#Now we only import the things we want while also iincreasing performance and start-up time
Comment

PREVIOUS NEXT
Code Example
Python :: python automation to sort files 
Python :: basic decorator example 
Python :: windows py SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate 
Python :: empty show non python 
Python :: lists as parameters in stats.f_oneway 
Python :: change between two python 3 version in raspberrry pi 
Python :: crank nicholson scheme python 
Python :: fichier python pour brython 
Python :: grouped box plot in python 
Python :: change the surface color rhinopython 
Python :: python multiline code dot 
Python :: spacy vietnamese 
Python :: finns = False 
Python :: np.linalg.eigvals positive check python 
Python :: function used in python 
Python :: python - dataframe columns is a list - drop 
Python :: how is pythons glob.glob ordered list 
Python :: pltoly boxlpot 
Python :: work day prior to date python 
Python :: What are zinc bandages used for? 
Python :: import data from website pandas python medium 
Python :: python code for calculating probability of random variable 
Python :: jwt authentication python flask 
Python :: dream manhunt 
Python :: how to see a full row in pandas 
Python :: remove grid from 3d plots 
Python :: how to get id of user discord.py 
Python :: quadre 
Python :: 52277-36880 
Python :: py2-pip (no such package) required by world py2-pip 
ADD CONTENT
Topic
Content
Source link
Name
6+6 =