POST 1 of 5 MorningPythonConcept
Stop writing C-style loops in Python
I can spot a developer who came to Python from Java or C in two seconds, just by looking at their loops.
for i in range(len(lst)):
print(lst[i])
That's a C loop in Python clothing. It works, but it's writing C with extra steps. The Pythonic version is one line shorter and impossible to off-by-one:
for item in lst:
print(item)
Need the index too? Use enumerate. for i, item in enumerate(lst): gives you both. Don't reach for range(len()) — that's a habit from languages where you HAD to track indices. Python iterates over iterables natively.
Need two parallel lists? zip is the answer. for a, b in zip(xs, ys): gives you pairs. Python 3.10 added zip(xs, ys, strict=True), which raises if the two iterables have different lengths. Use it. Silent zip-truncation is a bug class.
Need to walk over chunks of a list? itertools.batched(lst, n) (Python 3.12+) yields tuples of n consecutive items. Before 3.12, you wrote a manual chunker. After, you don't.
The broader principle. Python's for-loop iterates over *values*, not over an integer index that you then use to retrieve values. Once you internalise this, your loops shrink, your bug surface shrinks, and your code reads like English.
The rare exception is when you genuinely need the index for arithmetic — e.g., comparing element i with element i+1. Even then, enumerate plus a sentinel is usually cleaner than range(len()).
It's a small habit. The amount of grief it saves a Python codebase, over years, is enormous. Break the C-style reflex.#AI#MachineLearning#Python#100DaysOfCode#BuildInPublic#PythonStyle#PythonBasics