1. Home
  2. Explore
  3. Computer Science
  4. Essential Python Concepts

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Essential Python Concepts

Essential Python Concepts

1. Mutable and Immutable Objects

A Python object is immutable if its contents cannot be changed after it is created. A mutable object can be modified in place.

Common immutable types

  • str — strings

  • int — integers

  • float — floating-point numbers

  • bool — Boolean values

  • bytes

  • tuple

Common mutable types

  • list

  • set

  • dict — dictionaries

  • Many objects provided by third-party libraries

The distinction matters when variables refer to the same object.

Reassignment versus mutation

With an immutable object, an operation that appears to change a value actually creates or refers to a different object and assigns it to the variable. The original object is not modified.

x = (1, 2)
y = x

x = (1, 2, 3)

Here, reassigning x does not change what y refers to. y still refers to the original tuple.

In general, assignment does not automatically copy an object. It binds a variable name to an object. With immutable values, however, the object itself cannot be altered in place, so changing a variable typically means rebinding that name to another value.

Mutable objects and aliases

When one variable is assigned to another, both names can refer to the same mutable object:

x = [1, 2]
y = x

x[0] = 100

Because x and y refer to the same list, the mutation is visible through either name. Both variables now show [100, 2].

This shared reference is sometimes described as an alias: two names provide access to the same underlying object.

Mutable arguments and side effects

A function that receives a mutable object can modify the object in place. The change remains visible to the caller.

def sort_numbers(numbers):
    numbers.sort()

values = [3, 1, 2]
sort_numbers(values)

The sort() method changes the original list, so values becomes [1, 2, 3]. The function has produced a side effect: it changed an object beyond simply returning a result.

A function’s side effects may be intentional, but they should be understood and made clear. If the original list should remain unchanged, the function can work with a copy instead:

def sorted_numbers(numbers):
    return sorted(numbers)

sorted() returns a new sorted list, leaving the input list unchanged.

Key takeaway: Reassigning a variable and mutating an object are different operations. When multiple variables refer to the same mutable object, an in-place change through one variable is visible through the others.


2. List Comprehensions

A list comprehension is a compact way to construct a list by applying an expression to values produced by an iterable. It often expresses the same idea as a loop that appends values to a list.

Basic form

[i for i in range(10)]

This creates a list containing the integers from 0 through 9. The general structure is:

[expression for item in iterable]
  • The expression determines what value is added to the resulting list.

  • The for clause iterates over the input iterable.

  • The result is a new list containing one expression result for each iteration.

For example:

[square for square in range(5)]

produces the values generated by the expression for each number in the range.

Filtering values with a condition

A comprehension can include an if condition after the for clause:

[i for i in range(10) if i % 2 == 0]

The condition determines whether an item is included. This example produces the even numbers from 0 through 8; 10 is excluded because range(10) stops before 10.

The filtered form is:

[expression for item in iterable if condition]

The condition is a filter: items that do not satisfy it contribute nothing to the output list.

Nested comprehensions

A comprehension can appear inside another comprehension, which is useful for constructing nested lists:

[[j for j in range(5)] for i in range(10)]

The inner comprehension creates a list for each iteration of the outer comprehension. The result is a list of ten lists, each containing the values generated by range(5).

Nested comprehensions can become difficult to read. A conventional loop may be clearer when the logic has several steps or conditions.

Key takeaway: A list comprehension combines list construction, iteration, and optionally filtering. It is concise, but clarity is more important than compressing complex logic into one line.


3. Function Parameters and Arguments

A parameter is a name in a function definition. An argument is a value supplied when the function is called.

def describe(x, y):
    ...
    
describe(1, 2)

Here, x and y are parameters; 1 and 2 are arguments.

Required positional parameters

Parameters without default values are required unless the call supplies them by keyword. When values are passed positionally, they are assigned according to order.

def describe(x, y):
    print(x, y)

describe(1, 2)

In this call, x receives 1 and y receives 2.

Keyword arguments

Arguments can be supplied by naming the parameter:

describe(y=2, x=1)

Keyword arguments associate values with parameters by name, so their order in the call does not determine which parameter receives each value.

Positional arguments must come before keyword arguments in a function call:

describe(1, y=2)  # valid

A positional argument after a keyword argument is invalid:

# describe(x=1, 2)  # invalid

Optional parameters and default values

A parameter becomes optional when its definition gives it a default value:

def greet(name, punctuation="!"):
    print(name, punctuation)

The caller may omit punctuation; it then receives the default value. If the caller supplies a value, that value is used instead.

greet("Sam")       # uses "!"
greet("Sam", "?")  # uses "?"

A parameter with a default value is optional to provide, but it still has a value inside the function. Parameters without defaults remain required.

Collecting extra positional arguments with *args

A parameter written with a single asterisk, commonly named *args, collects extra positional arguments into a tuple:

def show(first, second, *args):
    print(first, second, args)

show(1, 2, 3, 4)

Here, first is 1, second is 2, and args is the tuple (3, 4). The name args is conventional rather than mandatory; the asterisk provides the special behavior.

A function can also use *args without other positional parameters to accept zero or more positional arguments.

Collecting extra keyword arguments with **kwargs

A parameter written with two asterisks, commonly named **kwargs, collects extra keyword arguments into a dictionary:

def show_options(**kwargs):
    print(kwargs)

show_options(color="blue", enabled=True)

The function receives a dictionary whose keys are the keyword names and whose values are the corresponding arguments.

The names args and kwargs are conventions. The significant syntax is * or **.

Combining parameters

A function can accept named parameters along with extra positional and keyword arguments:

def configure(a, b, *args, enabled=False, **kwargs):
    ...

In a call, positional values fill the positional parameters first; additional positional values are collected by *args. Named values can supply parameters by keyword, while additional keyword values are collected by **kwargs. The exact kinds of parameters and their order determine which calls are valid.

Unpacking arguments in a function call

A single asterisk can unpack an iterable into separate positional arguments:

values = [1, 2]
describe(*values)

This behaves like calling describe(1, 2): the iterable’s elements are supplied as individual positional arguments.

Two asterisks can unpack a dictionary into keyword arguments:

options = {"x": 1, "y": 2}
describe(**options)

The dictionary’s keys must match accepted parameter names, unless the function accepts extra keywords through **kwargs. Each key becomes a keyword name, and its associated value is passed as that argument.

Key takeaway: *args collects extra positional arguments into a tuple, while **kwargs collects extra keyword arguments into a dictionary. In a call, *iterable and **dictionary perform the reverse operation by unpacking values into arguments.


4. The __name__ == "__main__" Guard

When Python runs a file, it assigns the special variable __name__ a value indicating how the file is being used.

  • If the file is run directly, its __name__ is set to "__main__".

  • If the file is imported as a module, its __name__ is set to the module’s name.

The condition below checks whether the file is being run directly:

if __name__ == "__main__":
    print("Run directly")

Code inside this block runs when the file is executed as the main program. It does not run merely because another file imports the module.

Why the guard is useful

A Python module may contain functions and classes intended for use by other files. It may also contain code that starts a program, sends a request, initializes an application, or performs another action. The guard keeps this direct-execution behavior from happening automatically during import.

For example:

# utility.py

def add(a, b):
    return a + b

if __name__ == "__main__":
    print(add(2, 3))

Running utility.py directly prints the result. Importing add from utility.py makes the function available without executing the guarded print statement.

Code outside the guard—such as function and class definitions—is still processed when a module is imported. The guard does not prevent the entire file from being read; it controls whether the indented block is executed.

Key takeaway: The main guard separates code intended for direct execution from code intended to be imported and reused.


5. The Global Interpreter Lock (GIL)

The Global Interpreter Lock, or GIL, is a lock used by the standard CPython interpreter to control access to Python’s interpreter state. In the usual GIL-enabled CPython implementation, only one thread at a time can execute Python bytecode within a process.

Threads and CPU cores

A thread is a sequence of work that can be scheduled for execution within a program. Computers can have multiple CPU cores, and multiple cores can execute work in parallel when the workload and runtime permit it.

However, in a GIL-enabled CPython process, having multiple threads does not generally allow multiple threads to execute Python bytecode in parallel across CPU cores. Threads take turns holding the GIL.

Effect on CPU-bound work

CPU-bound work spends most of its time performing computation. If such a task is split among several Python threads, the GIL usually prevents those threads from executing Python bytecode simultaneously. As a result, dividing a CPU-heavy calculation among threads does not normally produce the parallel speedup that multiple CPU cores might otherwise provide.

For example, splitting a large sum into sections and assigning each section to a thread may not make a pure-Python calculation faster in a GIL-enabled CPython process. The threads still contend for the interpreter lock.

Threads can still be useful

The GIL does not mean that Python programs cannot use multiple threads. Threads can still be useful for I/O-bound work, such as waiting for network responses, reading files, or handling user input. While one thread is waiting for I/O, another can make progress. This can improve responsiveness or allow several waiting operations to be managed concurrently, even though only one thread executes Python bytecode at a time under the GIL.

Some extension modules perform work outside the GIL, and some tasks can therefore benefit from parallel execution even when called from Python threads.

Alternatives for CPU parallelism

For CPU-heavy work, common approaches include:

  • Multiprocessing: Use separate processes, which have separate interpreter instances and do not share one process-wide GIL.

  • Native or specialized libraries: Use libraries that perform computation in optimized native code and may release the GIL.

  • A free-threaded Python build: Some Python versions and builds offer an option designed to run without the traditional GIL, with different performance and compatibility considerations.

Key takeaway: The GIL limits parallel execution of Python bytecode by threads in standard GIL-enabled CPython. Threads can still help with I/O-bound concurrency, while CPU-bound parallelism often calls for processes or suitable native libraries.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent