Python operators determine how expressions evaluate; data structures determine how a program stores and accesses information. These topics belong together because an operator that is meaningful for one type may have a different meaning—or be unavailable—for another. A list supports indexed access and element membership, for example, while a dictionary maps hashable keys to values and preserves insertion order in modern Python. Learning the syntax without understanding mutability, equality and data shape leads to bugs that are hard to explain later.
This tutorial uses modern Python 3 behavior and small examples that can be tested in an interactive interpreter. It focuses on arithmetic, comparison, Boolean logic, identity, membership and the four core built-in collection families: lists, tuples, dictionaries and sets. The examples describe the ordinary built-in types; user-defined classes may implement operators through special methods, so a result is not always determined by the operator symbol alone.
Understand arithmetic and comparison expressions
Python supports ordinary arithmetic operators such as +, -, *, /, //, % and **. Division with / produces true division, while // performs floor division. This matters for negative values: -7 // 3 gives -3, not -2. The modulo operator follows the associated floor-division relationship. These details affect pagination, grid calculations and any algorithm that divides numbers into buckets.
total = 17
batch_size = 5
print(total / batch_size) # 3.4
print(total // batch_size) # 3
print(total % batch_size) # 2
print(2 ** 3) # 8
Operators have precedence. Multiplication ordinarily binds more tightly than addition, and parentheses let developers make intent explicit. When an expression is hard to read, prefer a named intermediate value to a puzzle involving many operator levels. Assignment expressions and in-place operators can be useful, but they should not hide state changes. In a team codebase, clarity is more valuable than minimizing line count.
Comparison operators include ==, !=, <, >, <= and >=. For built-in numeric values, the result is normally a Boolean. String comparison is lexicographic and based on Unicode code points rather than natural-language sorting. Python also supports chained comparisons such as 0 < x < 10, which expresses a range check clearly. Use explicit validation when values may be missing or of incompatible types.
Distinguish logical operators from bitwise operators
Logical operators and, or and not control Boolean-style reasoning using Python’s truth-value rules. The important nuance is that and and or generally return one of their operand objects, not automatically a Boolean. This is useful for selecting fallback values, but it can also produce subtle bugs when an empty list or zero is a valid value that should not be replaced.
name = ""
chosen = name or "Anonymous"
print(chosen) # Anonymous
items = []
if not items:
print("No items")
Use is or is not when checking identity with the singleton None; do not replace equality comparisons in ordinary application code with identity tests simply because two strings sometimes appear to reference the same object. Python may reuse certain immutable values internally, but that is not a contract for your logic. == asks whether objects compare equal according to their type; is asks whether they are the same object.
Bitwise operators such as &, |, ^, ~, << and >> work on integer bit patterns and can have overloaded meanings for other types. A bitwise operation is not interchangeable with logical and or or. In numerical libraries, an operator may perform element-wise operations rather than scalar truth testing. When working with such libraries, consult that type’s documentation and use parentheses around comparisons when appropriate.
Use lists when order and controlled mutation matter
A list is an ordered, mutable collection. It supports indexing, slicing, iteration and methods such as append, extend and pop. A list is a good default for a sequence whose elements may be added, removed or reordered. Unlike a tuple, it can change after creation. Unlike a set, it can contain duplicate values and supports positional access.
tasks = ["build", "test"]
tasks.append("deploy")
print(tasks[0]) # build
print(tasks[-1]) # deploy
print(tasks[1:]) # ['test', 'deploy']
Lists hold references to objects. Making a shallow copy creates a new list container, not copies of every nested object. If a list contains dictionaries and both lists share those dictionary objects, changing a nested value may be visible through both. This distinction is important for configuration, test fixtures and data transformations. Use a deep copy only when the semantics demand it; it can be expensive and may not be suitable for every object graph.
Membership with in tests whether a matching element is present. For a general list, this normally requires examining elements until the match is found. If frequent membership testing is the main operation and elements are hashable, a set may be a better choice. If positional order or duplicates matter, keep the list. Choosing a data structure should follow the operations and invariants the program needs.
Use tuples for fixed records and stable groupings
A tuple is an ordered, immutable sequence. It is useful for small fixed collections such as a coordinate pair, a returned value grouping or an identified record. Immutability means you cannot replace an element of the tuple after creation, but it does not freeze every mutable object stored inside it. A tuple containing a list still allows that inner list to change.
point = (12, 7)
x, y = point
print(x, y)
record = ("A1", ["queued"])
record[1].append("checked") # Inner list is still mutable
Tuple unpacking makes short assignments readable, but each position should have a clear meaning. If a record has many fields or is passed widely across a program, a dataclass or named tuple can make the structure more self-documenting. A data structure is successful when the code that consumes it can understand what the values mean, not merely when it occupies fewer bytes.
Use dictionaries for key-value relationships
A dictionary maps hashable keys to values. Dictionaries preserve insertion order in current Python 3 releases, but their core purpose remains lookup by key rather than position. A dictionary is suitable for configuration, object attributes represented as data, or associating identifiers with records. It requires thought about what a missing key means: direct indexing raises KeyError, while get can supply a fallback.
service = {"name": "api", "replicas": 2}
print(service["name"])
print(service.get("region", "not set"))
service["replicas"] = 3
A dictionary’s keys must have stable hash and equality behavior while stored. Immutable built-in values such as strings and suitably composed tuples are commonly used as keys; an ordinary list cannot serve as a key because it is unhashable. Changing the hash-relevant state of a custom key object while it is in a dictionary can break reliable lookup. This is one reason to prefer simple immutable identifiers for mapping keys.
Dictionaries can be iterated over keys, values or key-value pairs. Use items() when both the key and value are needed, and avoid mutating a dictionary’s size while iterating directly over it. For data received from an API, validate expected keys and value types; a successful JSON parse does not prove that the dictionary meets the application’s data contract.
Use sets for distinct elements and membership checks
A set holds distinct hashable elements. It supports union, intersection and difference operations and is often helpful for deduplication and membership testing. Sets do not promise positional order. A program that depends on the first element returned from a set has a design defect if that ordering matters. Converting a list to a set removes duplicates but also discards the original positional semantics.
required = {"build", "test", "scan"}
completed = {"build", "test"}
missing = required - completed
print(missing) # {'scan'}
Set operations express relationships clearly. To find shared tags, use intersection; to find identifiers in either group, use union; to find elements only in one group, use difference. The displayed order of a set is not guaranteed, so compare sets by content in tests rather than by their printed representation. If you need both reliable ordering and uniqueness, preserve order explicitly or choose a different representation.
Understand mutability, copying and operation cost
Mutability affects how functions communicate changes. When a function receives a list or dictionary and modifies it, callers holding the same object may observe the modification. When it receives an integer or string, a reassignment inside the function does not mutate the caller’s immutable value. Be clear whether a function returns a new collection or changes the one passed in. Many surprising bugs arise from assuming that all assignments make independent copies.
As a general rule, dictionary and set membership can offer average-case constant-time behavior when hashes are suitable; list membership is typically linear in the number of elements. That does not mean every dictionary operation has a fixed cost regardless of data, collisions or resizing. Algorithmic complexity is one input to a design decision, alongside readability, memory use and the need for stable order or duplicates.
Write tests for edge cases: an empty list, repeated values, a missing dictionary key, a nested mutable object, and a comparison between values of unexpected types. For business data, also consider how values are validated and represented before they enter a collection. Good Python code chooses structures to make illegal or ambiguous states harder to create, rather than relying entirely on the programmer remembering every special case.
Practice by building a small data-processing workflow
Imagine processing a batch of job records. Use a list to retain their arrival order, a dictionary to index them by identifier, and a set to track which identifiers have already been processed. Use arithmetic to calculate batch sizes, comparisons to reject invalid values, and Boolean conditions to control whether a record is eligible. This exercise forces a choice of collection based on the work it actually performs.
Then test duplicate identifiers, empty input, missing fields and retries. A dictionary built from records with duplicate IDs silently retains the later value for that key unless you explicitly detect duplicates. A set helps identify repeated IDs but will not remember the first arrival order. A list preserves order but does not provide the same keyed lookup. Explain these trade-offs as part of the solution; do not hide them behind a clever comprehension whose behavior is hard to inspect.
Python operators and data structures are not a memorization contest. Understand equality versus identity, the truth-value behavior of logical expressions, the mutability of nested objects and the operations your program needs most. Those fundamentals support clearer algorithms and safer application code as the system grows.
Language references: Python built-in types and Python expression semantics.