Skip to lesson
Python for JS Developers

Pythonic PatternsLesson 1 of 2

Idiomatic Python

3 min

Every language has its preferred style. Code can be correct but not idiomatic. These patterns are what separate "someone who writes JS in Python" from "a Python developer". Adopting them makes your code shorter and easier for other Python developers to read.

The biggest mindset shift: Python favors comprehensions, built-in functions, and plain loops over long method chains. Instead of arr.filter().map().reduce(), you reach for a comprehension plus sum(), max(), any(), or all(). And instead of checking sizes (arr.length > 0), you rely on truthiness (if arr:).

The collections module is your secret weapon. Counter counts things, defaultdict removes "does this key exist yet?" checks, and deque gives you fast appends and pops at both ends. For small record types, use a dataclass or typing.NamedTuple instead of a loose dict.

When you are unsure, write the plain loop first. If a comprehension or a built-in makes it clearer, switch; if it makes it cleverer but harder to read, keep the loop.

Quick reference

JavaScriptPythonNote
if (arr.length > 0)if arr:Truthiness check
arr.forEach((x, i) => ...)for i, x in enumerate(arr):enumerate gives the index
[a, b] = [b, a]a, b = b, aTuple swap
[1, 2, 3].includes(x)x in (1, 2, 3)Membership test
Object.fromEntries(keys.map((k, i) => [k, vals[i]]))dict(zip(keys, vals))zip + dict
Manual counting loopCounter(items)collections.Counter
(obj[k] ??= []).push(v)groups[k].append(v)defaultdict(list)

Side by side

JavaScript
// JavaScript patterns
if (arr.length === 0) { }
arr.forEach((item, i) => console.log(i, item));
[a, b] = [b, a];
if ([1, 2, 3].includes(x)) { }

const obj = Object.fromEntries(
  keys.map((k, i) => [k, vals[i]])
);

const counts = {};
for (const w of words) counts[w] = (counts[w] ?? 0) + 1;
Python
# Pythonic patterns
if not arr:                    # empty check
    pass
for i, item in enumerate(arr): # index + value
    print(i, item)
a, b = b, a                    # swap
if x in (1, 2, 3):             # membership
    pass

d = dict(zip(keys, vals))      # zip + dict

from collections import Counter
counts = Counter(words)        # count anything
top_3 = counts.most_common(3)

from collections import defaultdict
grouped = defaultdict(list)
for item in items:
    grouped[item.category].append(item)

Exercise

Real Python, running in your browser

Refactor this non-Pythonic code (my_list, x, y and text are already defined):

Starter code
# 1
if len(my_list) > 0:
    print("not empty")
# 2
i = 0
for item in my_list:
    print(str(i) + ": " + str(item))
    i = i + 1
# 3
temp = x
x = y
y = temp
# 4
result = []
for num in range(20):
    if num % 2 == 0:
        result.append(num * num)
# 5
word_freq = {}
for word in text.split():
    if word in word_freq:
        word_freq[word] += 1
    else:
        word_freq[word] = 1

Ctrl + Enter runCtrl + Shift + Enter checkTab indentEsc then Tab to leave the editorCtrl + / comment