All articles

Python Beginner Mistakes: float, Generators, True == 1 and More

Python Beginner Mistakes: float, Generators, True == 1 and More

Some beginner mistakes in Python look harmless: the code runs, and tests on a couple of examples pass. Then cents appear out of nowhere in calculations, a dictionary "loses" keys, memory climbs into gigabytes, and a function can't be reused. Below are the mistakes I see most often among beginners, with code examples and how to do it right. There are seven of them, plus a bonus eighth.

1. float where you need precision

What is 0.1 + 0.1 + 0.1? Anyone will say 0.3. Python says otherwise:

>>> 0.1 + 0.1 + 0.1
0.30000000000000004

This isn't a Python bug but a property of floating-point numbers: 0.1 can't be represented exactly in binary. For graphics and physics you can ignore such an error. But imagine a banking app where a million transactions a minute recalculate fees for years: tiny deviations add up to real money.

For money and anything where precision matters, use Decimal, and create it from a string:

from decimal import Decimal

print(Decimal("0.1") * 3)   # 0.3
print(Decimal(0.1))         # 0.1000000000000000055511151231257827021181583404541015625

Decimal(0.1) takes an already imprecise float and faithfully keeps its error. When I wrote a project for the Binance exchange API, I calculated fees and the best price with Decimal.

2. A list where a generator is enough

List comprehensions are convenient, but they build the whole list in memory at once. If you need the result only once — for example, to sum it — a generator is enough: the same characters, just round brackets.

import sys

squares_list = [x * x for x in range(1_000_000)]
squares_gen = (x * x for x in range(1_000_000))

print(sys.getsizeof(squares_list))  # about 8 MB — and that's without the numbers themselves
print(sys.getsizeof(squares_gen))   # about 200 bytes

total = sum(x * x for x in range(1_000_000))

A generator yields values one at a time and doesn't store them. The memory difference is tens of thousands of times, and getsizeof for a list only counts the array of references — the number objects themselves take even more. Speed is about the same; the gain is in memory. More on how lists eat memory in why a Python list can eat all your memory.

3. round just for pretty output

A common sight: data comes in as a string or a number with a long tail of digits, and it's passed through round only to display it nicely.

balance = 1532.4871
print(round(balance, 1))   # 1532.5 — a number
print(f"{balance:.1f}")    # 1532.5 — a string for display

If a number only needs to be shown, format it in an f-string: it's simpler and doesn't change the value itself. And round has surprises: it rounds half to even (round(2.5) == 2, round(1.5) == 2), and round(2.675, 2) gives 2.67 because of the same binary error. For money — again, Decimal with an explicit rounding mode.

4. True and 1 as different dictionary keys

data = {1: "one", True: "true", 0: "zero", False: "false"}
print(data)  # {1: 'true', 0: 'false'}

In Python True == 1 and False == 0, and they have the same hash. So for a dictionary they're the same key: the second assignment overwrites the first. A function that expects "zero" for the key 0 suddenly gets "false". Don't mix bool and int in dictionary keys or set elements — separate them by meaning or use string keys.

5. Names that clash with keywords and built-ins

Keywords — class, def, in, with, del and others — can't be used as variable names: that's an immediate SyntaxError. And the editor doesn't always highlight the problem in advance. import keyword; print(keyword.kwlist) shows the full list for your version.

Names of built-in functions are worse: list, id, input, type, sum. You can overwrite them, and the error surfaces much later:

list = [1, 2, 3]
items = list(range(3))  # TypeError: 'list' object is not callable

Give variables names that don't even resemble built-ins: user_ids instead of id, items instead of list.

6. A function that opens the file itself

def write_report(path):
    with open(path, "w") as f:
        f.write("report")

It looks fine, but the function has three limitations at once. It always opens the file itself, even if the calling code already has it open. It decides the open mode for the user. And it only works with regular files: you can't pass a gzip archive, a temporary file or an in-memory buffer.

It's more flexible to accept an already open file object:

import gzip
import io
import tempfile


def write_report(f, lines):
    for line in lines:
        f.write(f"{line}\n")


with open("report.txt", "w") as f:
    write_report(f, ["ok"])

with gzip.open("report.txt.gz", "wt") as gz:
    write_report(gz, ["ok"])

with tempfile.TemporaryFile("w+") as tmp:
    write_report(tmp, ["ok"])

buffer = io.StringIO()
write_report(buffer, ["ok"])  # handy in tests

The function becomes universal, it's easy to test with io.StringIO, and closing the file is handled by whoever opened it, via with.

7. Tuples with "magic" indexes

user = ("Anna", 30, False)
print(user[2])  # what is this, anyway?

While the tuple is created on the line above, you can still guess. If it came from another module, user[2] tells you nothing. The solution is named tuples. The best option is typing.NamedTuple with types, default values and even methods:

from typing import NamedTuple


class User(NamedTuple):
    name: str
    age: int
    is_admin: bool = False

    def greeting(self) -> str:
        return f"Hello, {self.name}"


user = User("Anna", 30)
print(user.age, user.is_admin, user.greeting())

The object is still immutable and as lightweight as a tuple, but the code reads without comments. There's also the older option — collections.namedtuple, without type annotations.

8. Bonus: optimizing by eye

The last mistake is optimizing without measuring. For example, it seems obvious that numpy is always faster. But max(np_array) — the built-in max iterating over a numpy array element by element — is slow, while np_array.max() is many times faster. And creating a numpy array from a list also takes time.

line_profiler helps you find out where time actually goes: it shows the time of each line in a function marked with the @profile decorator:

pip install line_profiler
kernprof -l -v script.py

Measure first, then optimize the line that takes 40% of the time, not the one that takes half a percent.

Summary

Mistake The right way
float for money Decimal("0.1")
A list for a single pass A generator
round for display An f-string f"{x:.2f}"
True and 1 as keys Don't mix key types
Names like list, id, in Meaningful names
The function opens the file itself Accept a file object
user[2] NamedTuple
Optimizing by eye A profiler

Many of these mistakes disappear once you start designing code around clear classes and interfaces rather than a pile of functions passing tuples around. That's what my Python OOP course is about — from OOP basics to SOLID and design patterns.

Sources