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 :: how to convert .py into .exe through pytohn scripts 
Python :: if something in something python example 
Python :: Discord.py - change the default help command 
Python :: creating dynamic variable in python 
Python :: python left string 
Python :: python infinite loop 
Python :: pandas splitting the data based on the day type 
Python :: scipy cdf example 
Python :: how to print the 3erd character of an input in python 
Python :: python excel sheet 
Python :: AttributeError: __enter__ in python cde 
Python :: Display vowels in a string using for loop 
Python :: simple click counter in python 
Python :: forward checking algorithm python 
Python :: godot variablen einen wert hinzufügen 
Python :: endgame 
Python :: how to count categories in a csv command line 
Python :: stackoverflow ocr,cropping letters 
Python :: incremental betekenis 
Python :: how to upgrade pip in cmd 
Shell :: restart apache ubuntu 
Shell :: uninstall node js in ubunt 
Shell :: how to remove node_modules from git 
Shell :: upgrade pandas version 
Shell :: remove docker container 
Shell :: rust change to nightly 
Shell :: ubuntu flush dns 
Shell :: windows kill port 
Shell :: install yarn globally 
Shell :: check if nginx is running 
ADD CONTENT
Topic
Content
Source link
Name
3+8 =