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 builtwith 
Python :: sklearn euclidean distance 
Python :: sort dict based on other list 
Python :: python all any example 
Python :: call methods from within a class 
Python :: optimize python code 
Python :: how to create a variable that represents any integer in python 
Python :: Use the correct syntax to print the first item in the fruits tuple. 
Python :: printing with format 
Python :: python global keyword 
Python :: how to select number by twos in a list python next to each 
Python :: smma python 
Python :: how to open link in new tab selenium python 
Python :: Return an RDD with the keys of each tuple. 
Python :: slug 
Python :: generate 50 characters long for django 
Python :: Convert the below Series to pandas datetime : DoB = pd.Series(["07Sep59","01Jan55","15Dec47","11Jul42"]) 
Python :: The current Numpy installation fails to pass a sanity check due to a bug in the windows runtime. 
Python :: access dynamicall to name attribute python 
Shell :: git ignore permission changes 
Shell :: push empty commit 
Shell :: ubuntu uninstall redis 
Shell :: how to restart nginx 
Shell :: Warning: heroku update available from 7.47.4 to 7.47.5 
Shell :: uninstall material ui react 
Shell :: install grunt mac 
Shell :: ubuntu play on linux install 
Shell :: nonexistentpath data directory /data/db not found 
Shell :: download filezilla in ubuntu 
Shell :: jq on mac 
ADD CONTENT
Topic
Content
Source link
Name
3+6 =