Essential Python Tips and Tricks from A to Z
An extensive collection of Python programming tips and tricks, ranging from built‑in functions like all/any and collections to advanced features such as type hints, virtual environments, and third‑party libraries, presented alphabetically to help developers quickly enhance their code efficiency and readability.
This article gathers a wide range of useful Python tips and tricks, organized alphabetically, to help developers improve productivity and code quality.
ALL OR ANY
Python’s readability makes it popular; the all and any functions are handy for checking iterable contents.
x = [True, True, False]
if any(x):
print("At least one True")
if all(x):
print("Not one False")
if any(x) and not all(x):
print("At least one True and one False")BASHPLOTIB
Install bashplotlib to draw plots directly in the console.
$ pip install bashplotlibCOLLECTIONS
The collections module provides specialized container datatypes such as OrderedDict and Counter.
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
Use dir() to inspect the attributes of any Python object.
>> dir()
>>> dir("Hello World")
>>> dir(dir)More details: Python docs – dir()
EMOJI
Install the emoji package to work with emoticons.
$ pip install emojiExample:
from emoji import emojize
print(emojize(":thumbs_up:"))FROM_FUTURE_IMPORT
The __future__ module lets you import features from upcoming Python versions.
from __future__ import print_function
print("Hello World!")GEOPY
The geopy library simplifies geocoding and distance calculations.
$ pip install geopyExample usage:
from geopy import GoogleV3
place = "221b Baker Street, London"
location = GoogleV3().geocode(place)
print(location.address)
print(location.location)HOWDOI
The howdoi command‑line tool fetches quick answers from StackOverflow.
$ pip install howdoi
$ howdoi vertical align css
$ howdoi for loop in java
$ howdoi undo commits in gitNote: it returns only the top‑voted answer, which may not always be the most suitable.
INSPECT
The inspect module can retrieve source code, module information, and line numbers of objects.
import inspect
print(inspect.getsource(inspect.getsource))
print(inspect.getmodule(inspect.getmodule))
print(inspect.currentframe().f_lineno)JEDI
Jedi provides static analysis and autocompletion for Python editors.
**KWARGS
Using **kwargs allows a dictionary to be expanded into named arguments.
dictionary = {"a": 1, "b": 2}
def someFunction(a, b):
print(a + b)
return
# both calls are equivalent
someFunction(**dictionary)
someFunction(a=1, b=2)LIST COMPREHENSIONS
List comprehensions create lists in a concise, readable way.
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
The built‑in map() function applies a function to each item of an iterable.
x = [1, 2, 3]
y = map(lambda x: x + 1, x)
# prints out [2, 3, 4]
print(list(y))NEWSPAPER3K
The newspaper3k library extracts articles, metadata, and images from online news sites.
$ pip install newspaper3kOPERATOR OVERLOADING
Define special methods like __gt__ and __lt__ to customize the behavior of operators.
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 – + not defined
something + nothingPPRINT
The pprint module pretty‑prints complex data structures.
import requests
import pprint
url = 'https://randomuser.me/api/?results=1'
users = requests.get(url).json()
pprint.pprint(users)QUEUE
The queue module implements FIFO, LIFO, and priority queues for multithreaded programs.
__repr__
Implement __repr__ to provide a readable string representation of objects.
>> 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
The sh library lets you run shell commands as if they were Python functions.
import sh
sh.pwd()
sh.mkdir('new_folder')
sh.touch('new_file.txt')
sh.whoami()
sh.echo('This is great!')TYPE HINT
Python 3.5+ supports optional type hints to improve code clarity and enable static analysis.
def addTwo(x: int) -> int:
return x + 2
from typing import List
Vector = 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 result
x = [[1.0, 0.0], [0.0, 1.0]]
y = [[2.0, 1.0], [0.0, -2.0]]
z = addMatrix(x, y)UUID
Generate universally unique identifiers with the uuid module.
import uuid
user_id = uuid.uuid4()
print(user_id)VIRTUAL ENVIRONMENTS
Create isolated Python environments to manage different project dependencies.
python -m venv my-project
source my-project/bin/activate
pip install all-the-modulesWIKIPEDIA
The wikipedia package provides a simple API to fetch Wikipedia pages.
import wikipedia
result = wikipedia.page('freeCodeCamp')
print(result.summary)
for link in result.links:
print(link)YAML
Use PyYAML to read and write YAML files, a superset of JSON.
$ pip install pyyaml
import yamlZIP
The built‑in zip() function aggregates elements from multiple iterables into tuples.
keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))Mastering these concise Python techniques will help you become more efficient and confident in writing clean, maintainable code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
