0% found this document useful (0 votes)
1 views4 pages

Doc6 Python One Liners

Uploaded by

Swetha Arendla
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views4 pages

Doc6 Python One Liners

Uploaded by

Swetha Arendla
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python One-Liners & Tips: A Developer’s

Toolkit
Introduction
Python’s expressive syntax makes it possible to accomplish complex tasks in
surprisingly few lines. This guide collects the most useful patterns, idioms,
and one-liners that every Python developer should know.

Data Structures
Lists
# List comprehension with filter
evens = [x for x in range(100) if x % 2 == 0]

# Flatten nested list


flat = [item for sublist in nested for item in sublist]

# Remove duplicates while preserving order


unique = list([Link](items))

# Chunk a list into groups of n


chunks = [lst[i:i+n] for i in range(0, len(lst), n)]

# Transpose a matrix (list of lists)


transposed = list(zip(*matrix))

# Get every nth element


every_third = lst[::3]

# Reverse a list
reversed_list = lst[::-1]

Dictionaries
# Dictionary from two lists
d = dict(zip(keys, values))

# Merge dictionaries (Python 3.9+)


merged = dict1 | dict2

# Dictionary comprehension
squared = {x: x**2 for x in range(10)}

# Invert a dictionary
inverted = {v: k for k, v in [Link]()}

# Default dictionary for counting


from collections import defaultdict
counts = defaultdict(int)
for item in items:
counts[item] += 1

Sets and Counters


# Count occurrences and find most common
from collections import Counter
word_counts = Counter(words)
top_5 = word_counts.most_common(5)

# Set operations
common = set_a & set_b # intersection
all_items = set_a | set_b # union
only_in_a = set_a - set_b # difference

File I/O
# Read entire file
content = open('[Link]').read()

# Read lines into list (stripped)


lines = open('[Link]').read().splitlines()

# Write JSON with formatting


import json
[Link](data, open('[Link]', 'w'), indent=2, ensure_ascii=False)

# Read JSON
data = [Link](open('[Link]'))

# Read CSV into list of dicts


import csv
rows = list([Link](open('[Link]')))

# Read/write with pathlib (modern approach)


from pathlib import Path
text = Path('[Link]').read_text()
Path('[Link]').write_text('hello world')

# Process large files line by line (memory efficient)


with open('[Link]') as f:
errors = [line for line in f if 'ERROR' in line]
String Manipulation
# Multi-line string formatting
message = f"""
Hello {name},
Your order #{order_id} has been shipped.
Expected delivery: {date:%B %d, %Y}
"""

# Remove prefix/suffix (Python 3.9+)


filename = "report_2026.csv".removesuffix(".csv")

# Pad strings
padded = "42".zfill(5) # "00042"
centered = "title".center(20) # " title "

# Regular expressions
import re
emails = [Link](r'\b[\w.]+@[\w.]+\.\w+\b', text)
cleaned = [Link](r'\s+', ' ', messy_text).strip()

Functional Patterns
# Sort by multiple keys
students = sorted(students, key=lambda s: (-s['grade'], s['name']))

# Map and filter


names = list(map([Link], raw_names))
adults = list(filter(lambda p: p['age'] >= 18, people))

# Reduce
from functools import reduce
product = reduce(lambda a, b: a * b, numbers)

Useful Tricks
# Swap variables
a, b = b, a

# Ternary expression
result = "yes" if condition else "no"

# Walrus operator (Python 3.8+)


if (n := len(data)) > 10:
print(f"Processing {n} items")

# Unpacking with star


first, *middle, last = [1, 2, 3, 4, 5]

# Dictionary unpacking for function args


config = {'host': 'localhost', 'port': 8080}
connect(**config)

# Context manager for timing


from contextlib import contextmanager
import time

@contextmanager
def timer(label):
start = time.perf_counter()
yield
print(f"{label}: {time.perf_counter() - start:.3f}s")

with timer("database query"):


results = [Link](query)

Date and Time


from datetime import datetime, timedelta

now = [Link]()
dt = [Link]("2026-06-29", "%Y-%m-%d")
formatted = [Link]("%B %d, %Y") # "June 29, 2026"
tomorrow = now + timedelta(days=1)
iso = [Link]()

© 2026 — Developer Reference Series

You might also like