A–Z of Useful Python Tricks
This article presents a curated A‑Z list of practical Python tricks—including built‑in functions, standard library modules, code snippets, and tips such as using collections, type hints, virtual environments, and command‑line utilities—to help developers write cleaner, more efficient code.
ALL OR ANY – Demonstrates the use of any() and all() to test iterables for truthy values, with examples showing conditional prints for different combinations of True and False.
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 – Shows how to install bashplotlib to draw plots directly in the terminal.
$ pip install bashplotlibCOLLECTIONS – Introduces the collections module, highlighting OrderedDict and Counter for ordered dictionaries and frequency counting.
from collections import OrderedDict, Counter
x = OrderedDict(a=1, b=2, c=3)
y = Counter("Hello World!")DIR – Shows how to use dir() to inspect attributes of objects, modules, or strings.
>> dir()
>>> dir("Hello World")
>>> dir(dir)EMOJI – Demonstrates installing emoji and using emojize to print emoji characters.
$ pip install emoji
from emoji import emojize
print(emojize(":thumbs_up:"))FROM_FUTURE_IMPORT – Explains that the __future__ module lets you import features from future Python versions, e.g., print_function.
from __future__ import print_function
print("Hello World!")GEOPY – Shows how to install geopy and use it to geocode an address, retrieve latitude, longitude, and other location data.
$ pip install geopy
from geopy import GoogleV3
place = "221b Baker Street, London"
location = GoogleV3().geocode(place)
print(location.address)
print(location.location)HOWDOI – Introduces the howdoi command‑line tool that fetches quick answers from StackOverflow without leaving the terminal.
$ pip install howdoi
$ howdoi vertical align css
$ howdoi for loop in java
$ howdoi undo commits in gitINSPECT – Describes the inspect module for retrieving source code, module information, and the current line number.
import inspect
print(inspect.getsource(inspect.getsource))
print(inspect.getmodule(inspect.getmodule))
print(inspect.currentframe().f_lineno)JEDI – Highlights the jedi library for code auto‑completion and static analysis, used by projects like IPython.
**KWARGS – Explains the **kwargs syntax for passing a dictionary as named arguments to a function.
dictionary = {"a": 1, "b": 2}
def someFunction(a, b):
print(a + b)
return
someFunction(**dictionary)
someFunction(a=1, b=2)LIST COMPREHENSIONS – Shows how list comprehensions create concise, readable lists, with examples for even/odd numbers and iterating over cities.
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 – Demonstrates using the built‑in map() function with a lambda to transform a list.
x = [1, 2, 3]
y = map(lambda x: x + 1, x)
print(list(y))NEWSPAPER3K – Introduces the newspaper3k library for extracting articles, metadata, and performing simple NLP on news sites.
$ pip install newspaper3k
# Example usage omitted for brevityOPERATOR OVERLOADING – Shows how to overload comparison operators ( __gt__, __lt__) in a custom class.
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)
something > nothing # True
something < nothing # FalsePPRINT – Recommends the pprint module for pretty‑printing complex data structures.
import requests
import pprint
url = 'https://randomuser.me/api/?results=1'
users = requests.get(url).json()
pprint.pprint(users)QUEUE – Explains Python's queue module for thread‑safe FIFO, LIFO, and priority queues.
__repr__ – Shows how defining __repr__ in a class provides a readable string representation for debugging.
class someClass:
def __repr__(self):
return "<some description here>"
someInstance = someClass()
print(someInstance)sh – Demonstrates the sh library for invoking shell commands as Python functions.
import sh
sh.pwd()
sh.mkdir('new_folder')
sh.touch('new_file.txt')
sh.whoami()
sh.echo('This is great!')TYPE HINT – Introduces type annotations (PEP 484) for function signatures and type aliases.
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 resultUUID – Shows generating a universally unique identifier using the uuid module.
import uuid
user_id = uuid.uuid4()
print(user_id)VIRTUAL ENVIRONMENTS – Explains creating isolated Python environments with venv to manage different project dependencies.
python -m venv my-project
source my-project/bin/activate
pip install all-the-modulesWIKIPEDIA – Shows using the wikipedia library to fetch page summaries and links programmatically.
import wikipedia
result = wikipedia.page('freeCodeCamp')
print(result.summary)
for link in result.links:
print(link)YAML – Introduces PyYAML for loading and dumping YAML data, which supports comments and complex structures.
$ pip install pyyaml
import yaml
# Usage examples omitted for brevityZIP – Demonstrates the built‑in zip() function to combine two lists into a dictionary and how to unzip with *zip.
keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))Mastering these concise Python tricks can significantly boost productivity and code readability for developers of all levels.
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.
