Python Essentials: List, Dictionary, Set Comprehensions, Unpacking, and Useful Built‑in Functions
This guide presents a concise collection of Python fundamentals, covering list, dictionary, and set comprehensions, various unpacking techniques, conditional expressions, common built‑in functions such as zip, enumerate, sorted, reversed, join, map, filter, any/all, min/max, sum, reduce, as well as useful modules like itertools, os, sys, time, collections, functools, heapq, bisect, json, re, and numpy, each illustrated with clear code examples.
List Comprehension Quickly create a list. squares = [x**2 for x in range(5)] print(squares) # [0, 1, 4, 9, 16]
Dictionary Comprehension Quickly create a dictionary. square_dict = {x: x**2 for x in range(5)} print(square_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Set Comprehension Quickly create a set. unique_chars = {char for char in "hello"} print(unique_chars) # {'h', 'e', 'l', 'o'}
List Unpacking Assign list elements to variables. a, b, c = [1, 2, 3] print(a, b, c) # 1 2 3
Tuple Unpacking Same technique for tuples. a, b, c = (1, 2, 3) print(a, b, c) # 1 2 3
Star Unpacking Capture multiple elements. a, *b, c = [1, 2, 3, 4, 5] print(a, b, c) # 1 [2, 3, 4] 5
Conditional Expression Ternary operator. result = "True" if 1 > 0 else "False" print(result) # True
zip() Combine multiple lists into a list of tuples. a = [1, 2, 3] b = [4, 5, 6] combined = list(zip(a, b)) print(combined) # [(1, 4), (2, 5), (3, 6)]
enumerate() Loop with index. for i, val in enumerate(['a', 'b', 'c']): print(i, val) # 0 a # 1 b # 2 c
sorted() Sort a list. numbers = [3, 1, 4, 1, 5, 9] sorted_numbers = sorted(numbers) print(sorted_numbers) # [1, 1, 3, 4, 5, 9]
reversed() Reverse a list. numbers = [1, 2, 3, 4, 5] reversed_numbers = list(reversed(numbers)) print(reversed_numbers) # [5, 4, 3, 2, 1]
set() Remove duplicates. numbers = [1, 2, 2, 3, 3, 3] unique_numbers = list(set(numbers)) print(unique_numbers) # [1, 2, 3]
join() Concatenate strings. words = ['hello', 'world'] sentence = ' '.join(words) print(sentence) # hello world
map() Apply a function to each element. numbers = [1, 2, 3] squared = list(map(lambda x: x**2, numbers)) print(squared) # [1, 4, 9]
filter() Filter elements by condition. numbers = [1, 2, 3, 4, 5] evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # [2, 4]
any() / all() Test existence or universality of a condition. numbers = [0, 1, 2, 3] has_zero = any(x == 0 for x in numbers) all_nonzero = all(x != 0 for x in numbers) print(has_zero, all_nonzero) # True False
min() / max() Find smallest and largest values. numbers = [1, 2, 3, 4, 5] print(min(numbers), max(numbers)) # 1 5
sum() Compute total of elements. numbers = [1, 2, 3, 4, 5] total = sum(numbers) print(total) # 15
reduce() Cumulative operation. from functools import reduce numbers = [1, 2, 3, 4, 5] product = reduce(lambda x, y: x * y, numbers) print(product) # 120
format() Classic string formatting. name = "Alice" age = 30 message = "My name is {} and I am {} years old.".format(name, age) print(message) # My name is Alice and I am 30 years old.
f‑string Modern string interpolation. name = "Alice" age = 30 message = f"My name is {name} and I am {age} years old." print(message) # My name is Alice and I am 30 years old.
with Context manager for safe file handling and exception handling example. with open('example.txt', 'w') as file: file.write('Hello, world!') try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero.")
@property Create read‑only attributes. class Person: def __init__(self, age): self._age = age @property def age(self): return self._age p = Person(30) print(p.age) # 30
lambda Anonymous function. add = lambda x, y: x + y print(add(1, 2)) # 3
itertools.chain() Concatenate iterators. from itertools import chain list1 = [1, 2, 3] list2 = [4, 5, 6] combined = list(chain(list1, list2)) print(combined) # [1, 2, 3, 4, 5, 6]
itertools.repeat() Repeat an element. from itertools import repeat repeated = list(repeat(1, 3)) print(repeated) # [1, 1, 1]
itertools.permutations() Generate permutations. from itertools import permutations perm = list(permutations([1, 2, 3], 2)) print(perm) # [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
itertools.combinations() Generate combinations. from itertools import combinations comb = list(combinations([1, 2, 3], 2)) print(comb) # [(1, 2), (1, 3), (2, 3)]
os File‑system operations. import os print(os.getcwd()) # current working directory
sys Access command‑line arguments. import sys print(sys.argv) # list of arguments
time Simple timing. import time start = time.time() time.sleep(1) end = time.time() print(end - start) # ~1.0
collections.Counter Count element frequencies. from collections import Counter counts = Counter([1, 2, 2, 3, 3, 3]) print(counts) # Counter({3: 3, 2: 2, 1: 1})
functools.partial Create a partially applied function. from functools import partial add_five = partial(lambda x, y: x + y, 5) print(add_five(10)) # 15
heapq Implement a priority queue. import heapq heap = [] heapq.heappush(heap, 1) heapq.heappush(heap, 3) heapq.heappush(heap, 2) print(heapq.heappop(heap)) # 1
functools.lru_cache Cache function results. from functools import lru_cache @lru_cache(maxsize=None) def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(10)) # 55
bisect Insert into a sorted list. import bisect lst = [1, 2, 4, 5] bisect.insort(lst, 3) print(lst) # [1, 2, 3, 4, 5]
json Serialize and deserialize JSON. import json data = {"name": "Alice", "age": 30} json_str = json.dumps(data) print(json_str) # {"name": "Alice", "age": 30}
re Regular expression matching. import re text = "The quick brown fox jumps over the lazy dog" match = re.search(r"quick (\w+) fox", text) print(match.group(1)) # brown
numpy Numerical computing. import numpy as np array = np.array([1, 2, 3]) print(array * 2) # [2 4 6]
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.