Essential Python Concepts


Essential Python Concepts

Maria
Welcome in. We’re walking through five Python concepts that show up often in real code and can trip up beginners and intermediate programmers: mutable versus immutable objects, list comprehensions, function arguments, the `__name__ == "__main__"` check, and the Global Interpreter Lock, or GIL.

Corey
Let’s start with mutability, because it helps explain some surprising behavior when variables and functions interact. An immutable object can’t be changed after it’s created; a mutable object can be modified. In Python, strings, integers, floats, booleans, bytes, and tuples are immutable, while lists, sets, and dictionaries are mutable.

Maria
Here’s the important distinction: assigning a value to another variable doesn’t itself change the object. With an immutable value, if we write `y = x` and later reassign `x` to a different value, `y` still refers to the original value. We changed what the name `x` refers to; we didn’t modify the immutable object.

Corey
And if we try to change one item inside a tuple, like assigning to `x[0]`, Python raises an error because tuples don’t support item assignment. That’s a direct example of immutability: the tuple’s contents can’t be changed in place.

Maria
Lists behave differently. If `x` is a list and we write `y = x`, both names refer to the same list object. So if we change an element through `x`, we’ll see that change when we look at `y` too. The assignment created another reference to the list, not a separate list.

Corey
That shared reference matters when we pass mutable objects into functions. Imagine a function receives a list of numbers and calls `numbers.sort()`. Sorting changes that list in place, so the list the caller passed in is now sorted too.

Maria
That’s called a side effect: the function modifies an object it received, and the change is visible outside the function. Sometimes that behavior is intended, but sometimes it surprises the person calling the function. So when you read or write Python, check whether a function is mutating a list, dictionary, or another mutable object.

Corey
Next up: list comprehensions. They’re a compact way to create a list by putting an expression and a loop together. For example, `[i for i in range(10)]` produces the numbers zero through nine.

Maria
The expression comes first—that’s the value placed into the new list—and then comes the iteration that supplies values to it. You can also nest comprehensions. For instance, a comprehension inside another comprehension can build a list of lists, such as several inner lists containing values from a range.

Corey
You can add a condition too. In `[i for i in range(10) if i % 2 == 0]`, the `if` keeps only values whose remainder after division by two is zero. So the result is the even numbers from zero up to, but not including, ten.

Maria
Comprehensions are common in Python, and they can make a short transformation easy to recognize. But a complicated comprehension can be harder to understand than a regular loop. The key is being able to read the expression, the iteration, and any condition—and to choose clarity when the compact version gets confusing.

Corey
Now let’s unpack function parameters and arguments. Parameters are the names in the function definition; arguments are the values you provide when you call the function. If we define `def example(x, y):`, then `x` and `y` are parameters.

Maria
The simplest way to provide arguments is positionally: `example(1, 2)` assigns one to `x` and two to `y`, in that order. You can also use keyword arguments, as in `example(y=2, x=1)`. Naming the parameters means the values don’t have to appear in the same order.

Corey
You can combine the two styles, but positional arguments must come before keyword arguments. For example, a call that supplies a positional value and then names another parameter is valid; putting another positional value after a keyword argument causes an error.

Maria
A parameter can also have a default value, like `z=10` in a function definition. That makes it optional when you call the function: if you don’t provide `z`, it uses ten. If a parameter has no default, it’s required, so leaving it out produces an error.

Corey
For a flexible number of positional arguments, Python uses `*args`. The extra positional values are collected into a tuple, and the function can receive none, one, or several of them. The name `args` is conventional; the asterisk is what enables this behavior.

Maria
For a flexible number of keyword arguments, use `**kwargs`. Those extra named values are collected into a dictionary, where the keyword is the key and its supplied value is the value. A function can use that dictionary to inspect or process the keyword arguments it received.

Corey
There’s also unpacking at the call site. Put one asterisk before a list or another iterable to pass its items as separate positional arguments. Put two asterisks before a dictionary to pass its entries as keyword arguments—so the dictionary’s keys need to match the function’s parameter names.

Maria
For example, if a function takes `a` and `b`, unpacking a two-item list with `*` supplies those two positional values. If it also takes `c` and `d`, unpacking a dictionary with `**` can supply those named values. It’s a handy way to pass data that’s already stored in a collection.

Corey
The fourth concept is the `if __name__ == "__main__":` check. Python sets a module’s `__name__` to `"__main__"` when you run that file directly. When another file imports the module, its `__name__` is instead the module’s name.

Maria
That distinction lets a file provide functions for other modules to import without automatically running its direct-run code. Put code such as a program’s startup action inside the `if __name__ == "__main__":` block. Then it runs when the file is launched directly, but not just because the file was imported.

Corey
Without that guard, a statement at the top level of a module runs when Python imports it. That can be unwanted if the statement starts a program or performs another action. The guard helps separate reusable definitions from code meant to run only when that file is the entry point.

Maria
Our last concept is the GIL: the Global Interpreter Lock. In the Python implementation being discussed here, the GIL means that only one thread at a time can execute Python code. So having multiple threads doesn’t automatically let CPU-heavy Python work run across multiple CPU cores at once.

Corey
Picture dividing a sum into sections and assigning each section to a different thread. In a language and setup that allow those threads to execute simultaneously on separate cores, that work could potentially finish faster. With the GIL, multiple threads can exist, but they can’t all execute Python code at the same time, so splitting CPU-bound work among them doesn’t provide that same parallel-execution speedup.

Maria
The takeaway is to recognize what the GIL does when you see threaded Python code: multiple threads do not necessarily mean multiple threads are executing Python code in parallel. And now we’ve covered the five concepts—object mutability, comprehensions, function argument patterns, the main-module guard, and the GIL—that help make production Python easier to read and reason about.

Ask anything
We've read this whole study set, so questions about it get the best answers.