Skip to content
  • Pythonic Code & Idioms · Python

Pythonic Code & Idioms

LearnViaNotes @learnvianotes· 2 min read

“Pythonic” code uses the language's features the way they were intended — shorter, clearer and usually faster. Interviewers notice.

Before → after

Instead ofWrite
for i in range(len(xs)): print(xs[i])for x in xs: print(x)
i = 0 … i += 1 inside a loopfor i, x in enumerate(xs)
if len(xs) == 0:if not xs:
if x == True: / if x == None:if x: / if x is None:
tmp = a; a = b; b = tmpa, b = b, a
result = [] + loop + appenda list comprehension
d[k] = d[k] + 1 if k in d else 1d[k] = d.get(k, 0) + 1 or Counter
s = '' + s += piece in a loop''.join(pieces)
open … close()with open(…) as f:
x > 0 and x < 100 < x < 10

EAFP vs LBYL

Idioms worth knowing

Python
nums = [4, 8, 15, 16, 23, 42]

print(sum(1 for n in nums if n % 2 == 0))         # 4
print(all(n > 0 for n in nums), any(n > 40 for n in nums))   # True True
print(max(enumerate(nums), key=lambda p: p[1]))    # (5, 42)

first, *rest = nums
print(first, len(rest))                            # 4 5

pairs = list(zip(nums, nums[1:]))                  # neighbouring pairs
print(pairs[:2])                                   # [(4, 8), (8, 15)]

counts = {}
for word in "to be or not to be".split():
    counts[word] = counts.get(word, 0) + 1
print(sorted(counts.items(), key=lambda kv: -kv[1])[:2])   # [('to', 2), ('be', 2)]

Readable over clever

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report