Python Tips and Tricks

Python Tips and Tricks

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.

It's high-level built-in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.

Here are some cool python tricks

Transpose a list - convert a list from row, column to column, row

>>> old_list = [[0,1,2],[10,11,12],[20,21,22] 
>>> transposed = list(list(x) for x in zip(*old_list)) 
>>> transposed 
[[0, 10, 20], [1, 11, 21], [2, 12, 22]]

Swap 2 variables

a, b = b, a

scripting

import sh
sh.pwd()
sh.mkdir('new_folder')
sh.touch('new_file.txt')
sh.whoami()
sh.echo('This is great!')

Create a single string from all the elements in list

a = ["Hello", "Hashnode"]
print(" ".join(a))

Print The File Path Of Imported Modules

import os
import socket

print(os)
print(socket)

Return Multiple Values From Functions

def x():
    return 1, 2, 3, 4
a, b, c, d = x()

print(a, b, c, d)

Evaluation time discrepancy

array = [1, 8, 15]
a = (x for x in array if array.count(x) > 0)
array = [2, 8, 22]
print(list(a))

Modifying a dictionary while iterating over it

x = {0: None}

for i in x:
    del x[i]
    x[i+1] = None
    print(i)

One Line If Without Else

condition = True
if condition:
    print('hi')

One Line Return If

def f(x):
    return None if x == 0

Enums In Python

class MyExample:  
    Code, Coffee, Eat = range(3)  

print(MyExample.Eat)  
print(MyExample.Code)  
print(MyExample.Coffee)

Check The Memory Usage Of An Object

import sys  
x = 1 
print(sys.getsizeof(x))

Python DeBugger

import pdb 
pdb.set_trace()

Nested loops

for a in list1: 
    for b in list2: 
        process(a,b)

Can be refactored to :

import itertools 
for a,b in itertools.product(a,b): 
    process(a,b)

Chaining Of Comparison Operators

n = 10
result = 1 < n < 20
print(result)
result = 1 > n <= 9
print(result)

One-Line Password Generator

from random import choice; print(''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789%^*(-_=+)') for i in range(12)]))

Did you find this article valuable?

Support Kush's Blog by becoming a sponsor. Any amount is appreciated!