10 Essential Python Code Snippets for Everyday Development
This article presents ten concise Python code snippets covering common tasks such as checking empty strings, converting strings to dates, deduplicating lists while preserving order, listing files, computing averages, reading files, building query strings, range checks, finding max indices, and converting lists to CSV strings.
1️⃣ Check if a string is empty:
def is_empty(s):
return not s.strip()2️⃣ Convert a string to a date (default format "%Y-%m-%d"):
from datetime import datetime
def str_to_date(date_str, format="%Y-%m-%d"):
return datetime.strptime(date_str, format)3️⃣ Remove duplicates from a list while preserving order:
def unique_list(lst):
seen = set()
return [x for x in lst if not (x in seen or seen.add(x))]4️⃣ Get all files in a directory (excluding sub‑directories):
import os
def list_files(dir_path):
return [f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))]5️⃣ Compute the average of a numeric list:
def average(numbers):
return sum(numbers) / len(numbers)6️⃣ Read the entire contents of a file:
def read_file(file_path):
with open(file_path, 'r') as file:
return file.read()7️⃣ Convert a dictionary to a URL query string:
def dict_to_query_string(d):
return '&'.join(f"{k}={v}" for k, v in d.items())8️⃣ Check whether a number falls within a given inclusive range:
def is_in_range(number, start, end):
return start <= number <= end9️⃣ Find the index of the maximum value in a list:
def find_max_index(lst):
return lst.index(max(lst))🔟 Convert a list to a comma‑separated string:
def list_to_csv(lst):
return ','.join(str(x) for x in lst)These small but handy utilities form a core part of every Python developer's toolbox.
Test Development Learning Exchange
Test Development Learning Exchange
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.