Python Coding Interview Questions

author image Hirely
at 05 Jan, 2025

Question: What are Python’s built-in data structures?

Answer:

Python provides several built-in data structures that are versatile and efficient for storing and manipulating data. These structures are flexible, easy to use, and optimized for various use cases. The main built-in data structures in Python are:


1. List

  • Description: A list is an ordered, mutable (changeable) collection of items. Lists can store elements of different data types (heterogeneous).
  • Syntax: my_list = [1, 2, 3, "hello", 3.14]
  • Key Features:
    • Ordered: Items maintain their order.
    • Mutable: You can change the items after the list is created.
    • Supports duplicates.
    • Indexing, slicing, and iterating.
    • Can hold heterogeneous data types.

Example:

my_list = [1, 2, 3, "hello", 3.14]
my_list.append(5)  # Adding an item
my_list[0] = 10    # Modifying an item
print(my_list)     # Output: [10, 2, 3, 'hello', 3.14, 5]

2. Tuple

  • Description: A tuple is similar to a list, but it is immutable (unchangeable). Tuples are often used to store collections of data that should not change.
  • Syntax: my_tuple = (1, 2, 3, "hello", 3.14)
  • Key Features:
    • Ordered: Items maintain their order.
    • Immutable: Cannot be modified after creation.
    • Supports duplicates.
    • Can hold heterogeneous data types.

Example:

my_tuple = (1, 2, 3, "hello", 3.14)
# my_tuple[0] = 10  # This would raise an error because tuples are immutable
print(my_tuple)  # Output: (1, 2, 3, 'hello', 3.14)

3. Set

  • Description: A set is an unordered collection of unique elements. Sets are useful for membership tests and removing duplicates from a collection.
  • Syntax: my_set = {1, 2, 3, "hello", 3.14}
  • Key Features:
    • Unordered: Items do not maintain any specific order.
    • Mutable: You can add or remove items.
    • No duplicates: Automatically removes duplicates.

Example:

my_set = {1, 2, 3, "hello", 3.14}
my_set.add(5)  # Adding an item
my_set.remove(2)  # Removing an item
print(my_set)  # Output: {1, 3, 5, 'hello', 3.14}

4. Dictionary

  • Description: A dictionary is an unordered collection of key-value pairs. Dictionaries are very efficient for lookups based on a key and are often used to store mappings or associations.
  • Syntax: my_dict = {"key1": "value1", "key2": "value2"}
  • Key Features:
    • Unordered: Items are stored based on hash values, and the order is not guaranteed (though as of Python 3.7+, insertion order is preserved).
    • Mutable: You can add, remove, and modify key-value pairs.
    • Keys must be unique and immutable (e.g., strings, numbers, tuples).
    • Values can be any data type (mutable or immutable).

Example:

my_dict = {"name": "John", "age": 30}
my_dict["age"] = 31  # Modifying a value
my_dict["city"] = "New York"  # Adding a new key-value pair
print(my_dict)  # Output: {'name': 'John', 'age': 31, 'city': 'New York'}

5. String

  • Description: A string is a sequence of characters, and it is an immutable data type. Strings are one of the most commonly used data types in Python.
  • Syntax: my_string = "hello"
  • Key Features:
    • Immutable: Once created, you cannot modify the individual characters.
    • Ordered: Characters maintain their order.
    • Supports indexing, slicing, and concatenation.

Example:

my_string = "hello"
print(my_string[0])  # Output: 'h'
print(my_string[1:4])  # Output: 'ell'

6. frozenset

  • Description: A frozenset is an immutable version of a set. Unlike regular sets, once a frozenset is created, its elements cannot be modified (no adding/removing items).
  • Syntax: my_frozenset = frozenset([1, 2, 3])
  • Key Features:
    • Immutable: No changes allowed after creation.
    • Unordered: Elements have no defined order.
    • No duplicates.

Example:

my_frozenset = frozenset([1, 2, 3, 2, 1])
print(my_frozenset)  # Output: frozenset({1, 2, 3})

Summary of Python’s Built-in Data Structures:

Data StructureTypeMutableOrderedUnique ItemsCommon Operations
ListSequenceYesYesNoappend(), pop(), index(), slice()
TupleSequenceNoYesNoindex(), slice()
SetSetYesNoYesadd(), remove(), intersection(), union()
DictionaryMappingYesYes (from Python 3.7)Yes (keys only)get(), keys(), values(), items()
StringSequenceNoYesYes (in terms of characters)slice(), concat()
FrozensetSetNoNoYesintersection(), union()

Choosing the Right Data Structure:

  • Lists are ideal when you need ordered collections and plan to modify the content frequently.
  • Tuples are useful when you want an ordered collection that should remain unchanged.
  • Sets are great for ensuring uniqueness and testing membership quickly.
  • Dictionaries are perfect for mapping keys to values and for efficient lookups.
  • Strings are the go-to type for text manipulation.
  • Frozensets are best when you need an immutable collection of unique elements.

Question: What is the purpose of the breakpoint() function in Python?

Answer:

The breakpoint() function in Python is a built-in function used for debugging. It provides a simple way to start an interactive debugging session at a specific point in the code, allowing the developer to inspect variables, evaluate expressions, and control the flow of execution.


Key Features of breakpoint():

  • Interactive Debugging: It allows you to pause the execution of the program and enter an interactive debugger session, typically using pdb (Python Debugger), which is the default debugger in Python.
  • Set Breakpoints: By calling breakpoint(), you insert a “breakpoint” in your code where execution will stop, and the debugger will take over.
  • Useful for Inspection: Once the program pauses at the breakpoint, you can inspect the state of the program, such as variable values and the call stack, and execute commands interactively to understand what is happening.

Example Usage:

def calculate_sum(a, b):
    result = a + b
    breakpoint()  # Program will pause here, and you can inspect variables
    return result

x = 5
y = 10
sum_result = calculate_sum(x, y)
print(sum_result)

Steps of Execution:

  1. When the breakpoint() function is executed, Python stops the execution and enters an interactive debugger.
  2. In the debugger, you can:
    • Inspect variables: You can check the values of variables like a, b, and result.
    • Evaluate expressions: You can try expressions like a + b or inspect other variables in the current scope.
    • Continue execution: You can continue the program using continue, step through the code line by line with step, or exit the debugger.

How it Works:

  • Python Debugger (pdb): By default, breakpoint() invokes the pdb module (if the environment variable PYTHONBREAKPOINT is not set to another debugger). Once invoked, you enter an interactive debugging session.
  • Custom Debugger: You can change the behavior of breakpoint() by setting the PYTHONBREAKPOINT environment variable to another debugger or debugging tool.

Example of Using pdb:

When the program reaches the breakpoint(), the debugger prompt will appear:

> /path/to/script.py(5)calculate_sum()
-> return result
(Pdb)

At the (Pdb) prompt, you can use several commands to inspect or control the flow:

  • n: Go to the next line of code.
  • s: Step into the function call.
  • c: Continue execution until the next breakpoint.
  • p <variable>: Print the value of a variable (e.g., p result).

Customizing breakpoint():

You can modify the default debugger that breakpoint() uses by setting the PYTHONBREAKPOINT environment variable:

  • Example: Using ipdb (Interactive Python Debugger) instead of pdb:

    export PYTHONBREAKPOINT=ipdb.set_trace

After this, when breakpoint() is called, it will invoke ipdb instead of the default pdb.


When to Use breakpoint():

  • During Development: It’s commonly used during the development phase to quickly inspect the program’s state and troubleshoot issues.
  • Dynamic Debugging: It is helpful when you want to start debugging at a specific place without needing to set up breakpoints manually in an IDE or editor.
  • Simplifies Debugging: breakpoint() provides a quick way to add breakpoints without the need for external tools or IDE support.

Summary:

  • The breakpoint() function is a built-in debugging tool in Python that pauses execution and starts an interactive debugger.
  • It simplifies debugging by allowing you to inspect the state of the program and control execution flow from the command line.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as Python interview questions, Python interview experiences, and details about various Python job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now