PYTHON Reference Guide
Revision Time: 4 mins

Useful One-Liners Reference

Practical single-line Python solutions for common data processing tasks.

Reverse a String
Return: str

Reverse a string using slice notation.

Used In: Palindrome checks, reversing tokens.

Syntax signature:s[::-1]
Code snippet:
python
text = 'pipeline'
print(text[::-1])
Expected Output:enilepip

Time Complexity: O(N)

Related Methods: reversed()

Remember: Slice with step -1 works on any sequence: strings, lists, tuples.
Remove Duplicates
Return: list

Deduplicate a list while preserving order using dict.fromkeys().

Used In: Deduplicating customer IDs, event log entries.

Syntax signature:list(dict.fromkeys(lst))
Code snippet:
python
ids = [3, 1, 2, 1, 3, 4]
unique = list(dict.fromkeys(ids))
print(unique)
Expected Output:[3, 1, 2, 4]

Time Complexity: O(N)

Related Methods: set()

Comparison:

dict.fromkeys() preserves order; set() is O(N) but unordered.

Remember: dict.fromkeys() preserves insertion order (Python 3.7+). Using set() is faster but loses order.
Flatten Nested List
Return: list

Flatten one level of nested lists into a single flat list.

Used In: Flattening API response arrays, combining CSV batches.

Syntax signature:[item for sub in nested for item in sub]
Code snippet:
python
batches = [[1, 2], [3, 4], [5]]
flat = [x for sub in batches for x in sub]
print(flat)
Expected Output:[1, 2, 3, 4, 5]

Time Complexity: O(N)

Related Methods: itertools.chain.from_iterable()

Remember: For deeply nested structures, use itertools.chain.from_iterable() or a recursive approach.
Swap Variables
Return: None

Swap two variable values without a temporary variable.

Used In: Sorting algorithms, pointer swaps.

Syntax signature:a, b = b, a
Code snippet:
python
x, y = 10, 20
x, y = y, x
print(x, y)
Expected Output:20 10

Time Complexity: O(1)

Related Methods: N/A

Remember: Python evaluates the right side fully before assignment — no temporary variable needed.
Count Frequencies
Return: Counter

Count occurrences of each element using Counter.

Used In: Log level aggregation, word frequency, status monitoring.

Syntax signature:Counter(iterable)
Code snippet:
python
from collections import Counter
logs = ['INFO', 'ERROR', 'INFO', 'WARNING', 'ERROR', 'ERROR']
print(Counter(logs).most_common(2))
Expected Output:[('ERROR', 3), ('INFO', 2)]

Time Complexity: O(N)

Related Methods: collections.Counter

Remember: Counter.most_common(n) returns the top n elements sorted by frequency.
Sort Dictionary by Value
Return: dict

Return a new dict sorted by its values in ascending or descending order.

Used In: Leaderboards, ranked reporting, priority queues.

Syntax signature:dict(sorted(d.items(), key=lambda x: x[1]))
Code snippet:
python
scores = {'Alice': 88, 'Bob': 95, 'Carol': 72}
sorted_scores = dict(sorted(scores.items(), key=lambda x: x[1], reverse=True))
print(sorted_scores)
Expected Output:{'Bob': 95, 'Alice': 88, 'Carol': 72}

Time Complexity: O(N log N)

Related Methods: sorted(), operator.itemgetter()

Remember: In Python 3.7+, dicts maintain insertion order, so sorting items then calling dict() works correctly.
Read Entire File
Return: str

Read a file's full contents into a string in one line.

Used In: Config loading, reading script templates.

Syntax signature:open(path).read()
Code snippet:
python
from pathlib import Path
content = Path('config.json').read_text(encoding='utf-8')
print(type(content))
Expected Output:<class 'str'>

Time Complexity: O(N)

Related Methods: Path.read_text()

Remember: Use pathlib.Path.read_text() for a cleaner, context-manager-free one-liner that handles encoding.
Filter Empty Strings
Return: list

Remove empty and whitespace-only strings from a list.

Used In: CSV row cleaning, removing blank form fields.

Syntax signature:[s for s in lst if s.strip()]
Code snippet:
python
fields = ['Alice', '', ' ', 'Bob', '']
clean = [s for s in fields if s.strip()]
print(clean)
Expected Output:['Alice', 'Bob']

Time Complexity: O(N)

Related Methods: filter()

Remember: s.strip() returns an empty string (falsy) for whitespace-only entries — no need for explicit == ''.
Find Duplicates
Return: set

Find all elements that appear more than once in a list.

Used In: Duplicate detection in user IDs, transaction dedup.

Syntax signature:{x for x in lst if lst.count(x) > 1}
Code snippet:
python
ids = [1, 2, 3, 2, 4, 3, 5]
dupes = {x for x in ids if ids.count(x) > 1}
print(sorted(dupes))
Expected Output:[2, 3]

Time Complexity: O(N^2) with count(); use Counter for O(N)

Related Methods: collections.Counter

Remember: For large lists, use Counter for O(N) performance instead of O(N^2) count() inside comprehension.
Merge Dictionaries
Return: dict

Merge two dicts into one (second dict overrides first on conflicts).

Used In: Config merging, default + override patterns.

Syntax signature:{**d1, **d2} or d1 | d2 (Python 3.9+)
Code snippet:
python
defaults = {'timeout': 30, 'retries': 3}
overrides = {'retries': 5, 'debug': True}
config = {**defaults, **overrides}
print(config)
Expected Output:{'timeout': 30, 'retries': 5, 'debug': True}

Time Complexity: O(N + M)

Related Methods: dict.update()

Remember: In Python 3.9+, use the | operator for the same result more readably.
Convert List to String
Return: str

Join a list of strings into a single delimited string.

Used In: Building CSV rows, constructing SQL fragments, file paths.

Syntax signature:sep.join(lst)
Code snippet:
python
parts = ['2026', '07', '12']
date_str = '-'.join(parts)
print(date_str)
Expected Output:2026-07-12

Time Complexity: O(N)

Related Methods: str.split()

Remember: join() is much faster than += concatenation — it allocates the full string in one step.
Dictionary Inversion
Return: dict

Swap keys and values to create a reverse-lookup dictionary.

Used In: Reverse code lookups, ID-to-name mappings.

Syntax signature:{v: k for k, v in d.items()}
Code snippet:
python
dept_code = {'Engineering': 'ENG', 'Data Science': 'DS'}
code_dept = {v: k for k, v in dept_code.items()}
print(code_dept['DS'])
Expected Output:Data Science

Time Complexity: O(N)

Common Mistakes: Duplicate values cause keys to be overwritten silently.

Remember: Only works correctly when all values are unique and hashable.
Transpose Matrix (zip)
Return: list

Transpose rows and columns of a 2D list using zip(*matrix).

Used In: Data pivoting, feature transposition.

Syntax signature:list(map(list, zip(*matrix)))
Code snippet:
python
matrix = [[1, 2, 3], [4, 5, 6]]
transposed = list(map(list, zip(*matrix)))
print(transposed)
Expected Output:[[1, 4], [2, 5], [3, 6]]

Time Complexity: O(N*M)

Related Methods: zip()

Remember: zip(*matrix) unpacks and pairs corresponding elements across rows — clean and memory-efficient.
Read CSV into List
Return: list[dict]

Load a CSV file into a list of dicts using csv.DictReader.

Used In: Quick CSV loading in ETL scripts.

Syntax signature:list(csv.DictReader(open(file)))
Code snippet:
python
import csv, io
data = 'name,dept\nAlice,DE\nBob,DS'
rows = list(csv.DictReader(io.StringIO(data)))
print(rows[0])
Expected Output:{'name': 'Alice', 'dept': 'DE'}

Time Complexity: O(N)

Related Methods: pandas.read_csv()

Remember: DictReader uses the first row as header keys automatically — each row becomes a dict.
Safe Dictionary Lookup
Return: T

Get a nested value from a dict with a fallback instead of raising KeyError.

Used In: Parsing API responses, reading optional config fields.

Syntax signature:d.get(key, default)
Code snippet:
python
response = {'status': 200, 'data': {'user': 'Alice'}}
name = response.get('data', {}).get('user', 'Unknown')
print(name)
Expected Output:Alice

Time Complexity: O(1)

Related Methods: dict.get()

Remember: Chain .get() calls for nested lookups — each returns {} fallback if a key is missing.