Python: Tips and Tricks!

bashplotlib

pip install bashplotlib

collections

from collections import OrderedDict, Counter# Remembers the order the keys are added!
x = OrderedDict(a=1, b=2, c=3)# Counts the frequency of each character
y = Counter("Hello World!")

dir

dir() 
dir("Hello World!")
dir(dir)

emoji

pip install emoji
from emoji import emojize
print(emojize(":thumbs_up:")

future

from __future__ import print_function
print("Hello World!")

geopy

pip install geopy
from geopy import GoogleV3

place = "Kedarnath"
location = GoogleV3().geocode(place)

print(location.address)
print(location.location)

howdoi

pip install howdoihowdoi place image in tkinter frame
howdoi read csv file in pandas

inspect

import inspect
print(inspect.getsource(inspect.getsource))
print(inspect.getmodule(inspect.getmodule))
print(inspect.currentframe().f_lineno)

Jedi

**kwargs

dictionary = {"a": 1, "b": 2}
def someFunction(a, b):
print(a + b)
return# these do the same thing:
someFunction(**dictionary)
someFunction(a=1, b=2)

List comprehensions

numbers = [1,2,3,4,5,6,7]
evens = [x for x in numbers if x % 2 is 0]
odds = [y for y in numbers if y not in evens]cities = ['London', 'Dublin', 'Oslo']def visit(city):
print("Welcome to "+city)for city in cities:
visit(city)

map

x = [1, 2, 3]
y = map(lambda x : x + 1 , x)# prints out [2,3,4]
print(list(y))

newspaper3k

Operator overloading

class Thing:
def __init__(self, value):
self.__value = value
def __gt__(self, other):
return self.__value > other.__value
def __lt__(self, other):
return self.__value < other.__value
something = Thing(100)
nothing = Thing(0)# True
something > nothing# False
something < nothing# Error
something + nothing

pprint

import requests
import pprint
url = 'https://randomuser.me/api/?results=1'
users = requests.get(url).json()
pprint.pprint(users)

Queue

__repr__

>>> file = open('file.txt', 'r')
>>> print(file)
<open file 'file.txt', mode 'r' at 0x10d30aaf0>
class someClass:
def __repr__(self):
return "<some description here>"someInstance = someClass()# prints <some description here>
print(someInstance)

sh

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

Type hints

def addTwo(x : Int) -> Int:
return x + 2
from typing import ListVector = List[float]
Matrix = List[Vector]def addMatrix(a : Matrix, b : Matrix) -> Matrix:
result = []
for i,row in enumerate(a):
result_row =[]
for j, col in enumerate(row):
result_row += [a[i][j] + b[i][j]]
result += [result_row]
return resultx = [[1.0, 0.0], [0.0, 1.0]]
y = [[2.0, 1.0], [0.0, -2.0]]z = addMatrix(x, y)

uuid

import uuiduser_id = uuid.uuid4()
print(user_id)

Virtual environments

python -m venv my-project
source my-project/bin/activate
pip install all-the-modules

wikipedia

import wikipediaresult = wikipedia.page('freeCodeCamp')
print(result.summary)
for link in result.links:
print(link)

xkcd

import antigravity

YAML

$ pip install pyyaml
import yaml

zip

keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhijeet Srivastav

CEO Techneophyte | Python Developer | ML Engineer | Data Scientist | Flutter Developer | Penetration Tester | Software Engineer at Infosys