Python Coding Interview Questions
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 afrozenset
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 Structure | Type | Mutable | Ordered | Unique Items | Common Operations |
---|---|---|---|---|---|
List | Sequence | Yes | Yes | No | append(), pop(), index(), slice() |
Tuple | Sequence | No | Yes | No | index(), slice() |
Set | Set | Yes | No | Yes | add(), remove(), intersection(), union() |
Dictionary | Mapping | Yes | Yes (from Python 3.7) | Yes (keys only) | get(), keys(), values(), items() |
String | Sequence | No | Yes | Yes (in terms of characters) | slice(), concat() |
Frozenset | Set | No | No | Yes | intersection(), 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:
- When the
breakpoint()
function is executed, Python stops the execution and enters an interactive debugger. - In the debugger, you can:
- Inspect variables: You can check the values of variables like
a
,b
, andresult
. - 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 withstep
, or exit the debugger.
- Inspect variables: You can check the values of variables like
How it Works:
- Python Debugger (
pdb
): By default,breakpoint()
invokes thepdb
module (if the environment variablePYTHONBREAKPOINT
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 thePYTHONBREAKPOINT
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 ofpdb
: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.
Tags
- Python
- Python interview questions
- Python decorators
- Global Interpreter Lock
- Memory management
- List vs tuple
- Shallow copy
- Deep copy
- Python generators
- Exception handling
- Lambda function
- Python namespaces
- File modes
- Static method
- Class method
- Serialization
- Python 2 vs Python 3
- Debugging
- Stack and queue in Python
- Serialization in Python
- Python data structures
- Python comprehensions
- Mutable vs immutable
- Python coding interview
- Python fundamentals
- Exception handling in Python