Python foundations

Python Data Types: Numbers, Strings, Lists, and More

Choose built-in Python types, convert text to numbers and flags, and understand mutability, equality, and type checks.

Python data types describe what a value can do. Use int for whole numbers, float for approximate measurements, str for text, and bool for true or false. A list keeps ordered items, a dict looks values up by key, and a set keeps distinct members. Convert text to a number only when the text represents a quantity you need to calculate with.

raw_count = "12"
count = int(raw_count)
assert type(raw_count) is str
assert type(count) is int
assert count + 3 == 15

The string preserves what arrived. The integer lets you add three and get 15. Leave identifiers as text when leading zeros matter. Converting a room code such as "002" to integer 2 loses the original formatting.

Choose the representation according to meaning

Store a timeline in a list when arrival order matters. Store room names by identifier in a dictionary when each room has a stable key. Use a set for questions about unique members, such as which rooms have reported at least once. A tuple is useful when a few positions form one value, such as a row and column.

If your domain permits missing data, None can mean that no value was supplied. Its meaning needs to be documented. Sometimes a missing field and a field explicitly set to null have different consequences. A dictionary membership test can preserve that distinction.

Convert input strings to numbers or Boolean values

Inputs from files, commands, and forms may look numeric while arriving as strings. "12" + "3" is "123", a valid text operation. Converting the strings with int before adding produces the numeric result. Do the parsing at the boundary so the program's main calculation sees one consistent type.

A string that says "false" is still a nonempty string. bool("false") returns True. If you are reading a text field that accepts exactly “true” and “false,” map those words explicitly. Handle any other word as an invalid input rather than silently guessing what its author meant.

def read_flag(raw):
    options = {"true": True, "false": False}
    text = raw.strip().casefold()
    if text not in options:
        raise ValueError("Expected true or false")
    return options[text]

assert read_flag(" FALSE ") is False

Separate identity, equality, and type

Two equal lists can be separate objects. [1, 2] == [1, 2] compares their contents and returns True. Use is when testing whether two references refer to the exact same object, such as value is None. Assumptions about whether an interpreter reuses certain integers or strings should play no role in an equality check.

isinstance(value, int) accepts an integer or an instance of an integer subclass. In Python, bool is a subclass of int, so isinstance(True, int) is true. If a numeric input must reject booleans, add that rule explicitly. Exact type comparisons can be appropriate for a strict format but are too restrictive for some general-purpose functions.

Understand changes to mutable values

A list can be edited in place, and every name referring to that same list sees the edit. A string method instead returns a string reflecting the operation. Assigning it to the same variable simply moves the variable's reference to the result.

This distinction matters when a function takes input from a caller. A function that appends to a list modifies a value it received. A function that reassigns its local parameter to a new list does not reassign the caller's name. Test a mutable input before and after the function call when the ownership rule matters.

Preserve precision and intent

An integer is a good fit for counts and discrete quantities. A floating-point number can express measurements and approximate ratios, but a decimal fraction may have no exact representation in binary floating point. If a calculation requires a defined decimal rounding policy, use decimal arithmetic or whole minor units with an explicit conversion rule.

A small boundary test does more than check whether conversion succeeds. Try the smallest meaningful value, a malformed value, and any blank or null representation the source permits. Check that the program still distinguishes data that arrived from a value it supplied as a default.

Convert the outer container and check the contents

Collection constructors interpret the input as a source of entries. list("red") returns the three individual characters. To keep one text value as a single entry, use ["red"]. list(some_dictionary) gives a list of keys, while list(some_dictionary.items()) gives key and value pairs. Neither automatically converts the types of those values.

That matters when processing records received as text. Suppose a record already has the right group of fields, but its count is still encoded as a string. Copying the record into a fresh dictionary does not parse that string. Convert the specific field after checking whether it arrived and whether a value of that form is permitted.

raw = {"room": "002", "visits": "5"}
record = {"room": raw["room"], "visits": int(raw["visits"])}
assert record == {"room": "002", "visits": 5}

Both inputs look numeric, but only one expresses a quantity. If the application later groups by room, preserving the label helps keep reports and raw rows comparable.

Use annotations to share the contract

A function annotation such as def scale(total: int) -> int: explains the expected input and output to a reader and to supporting tools. In ordinary Python it does not check or convert an argument on its own. When a value comes from an untrusted form or an external file, use a runtime validation rule even if the function also has annotations.

Type names describe technical capabilities. The contract also needs domain language. An int could represent an identifier, a count, or milliseconds. Calling the parameter elapsed_ms describes the unit. Writing a check like elapsed_ms >= 0 expresses another rule that the type alone cannot capture. A test at zero and just below it gives the rule a concrete example.

Keep surprising equivalences out of your data model

Different numeric types can compare equal, such as 1 == 1.0. In a dictionary those equal numeric keys can refer to the same entry. If the source considers the spelling of an identifier meaningful, retain it as text rather than converting it to a number. If the source expects different sorts of identifiers to share one mapping, give their keys a category as well as a value. A tuple such as ("room", 1) preserves the category without making it part of an ambiguous concatenated string.

Sources and further reading

Related reading

Browse Python foundations · Explore project tutorials

Search PythonProjects.org