Interview Prep

Top 20 Python Basic Interview Questions and Answers (2026 Guide)

Master the top 20 python basic interview questions: list vs tuple, mutable vs immutable, decorators, generators, and core coding questions with answers.

Anuj SainiSep 8, 202610 min read

Python is the leading language for data engineering, machine learning, and quantitative analysis. When interviewing for entry-level to mid-level roles, companies use basic Python screening questions to test whether candidates truly understand how the interpreter executes code or if they merely copy snippets without grasping underlying data structures.

Whether you are preparing for a live coding screen or a conceptual phone conversation, technical interviewers evaluate your code readability, familiarity with built-in data types, and defensive programming practices.

In this guide, you will master the top 20 python basic interview questions, complete with verified code snippets, memory model explanations, and practical prep strategies. To practice your analytical foundations, review our companion guides on SQL Interview Questions and Data Analyst Interview Questions 2026.


Monthly searches for Python basic interview screening questions

Python screening rounds filter out over 60% of candidates who struggle to explain memory mutability, slicing bounds, and generator semantics.


Top 20 Python Basic Interview Questions and Answers

Q1: What is the difference between mutable and immutable data types in Python?

Answer: A mutable object can have its state or contents modified in place after creation without changing its memory address (id()). An immutable object cannot be altered once instantiated; any modification creates a brand new object in memory.

  • Mutable Types: list, dict, set, bytearray
  • Immutable Types: int, float, bool, str, tuple, frozenset
python
# Mutable example (list id remains unchanged):
my_list = [1, 2, 3]
print(id(my_list))
my_list.append(4)
print(id(my_list))  # Identical memory address
 
# Immutable example (string modification creates new object):
my_str = "hello"
print(id(my_str))
my_str = my_str + " world"
print(id(my_str))  # Different memory address!

Q2: What is the difference between a List and a Tuple?

Answer:

  1. Mutability: Lists are mutable; tuples are immutable.
  2. Syntax: Lists use square brackets [1, 2]; tuples use parentheses (1, 2).
  3. Memory & Performance: Tuples are allocated in single memory blocks, making them lighter, faster to iterate, and memory-efficient.
  4. Dictionary Keys: Because tuples are immutable and hashable (if their contents are immutable), they can serve as dictionary keys. Lists can never be dictionary keys.

Q3: What is a List Comprehension, and why is it preferred over for loops?

Answer: A list comprehension provides a concise, readable syntax for creating new lists by transforming and filtering an iterable in a single line. It executes at C-speed in the Python interpreter, running faster than a manual .append() loop.

python
# Traditional loop:
squares = []
for x in range(10):
    if x % 2 == 0:
        squares.append(x ** 2)
 
# Pythonic List Comprehension:
squares = [x ** 2 for x in range(10) if x % 2 == 0]

Q4: What is the difference between == and is?

Answer:

  • == evaluates value equality: do two variables contain equivalent data?
  • is evaluates reference identity: do two variables point to the exact same object at the same memory address (id(a) == id(b))?
python
a = [1, 2, 3]
b = [1, 2, 3]
 
print(a == b)  # True (identical values)
print(a is b)  # False (two distinct list objects in memory)
 
c = a
print(a is c)  # True (both point to the same memory reference)

Always use is when checking against singleton constants like None: if x is None:.


Q5: What is the difference between Shallow Copy and Deep Copy?

Answer:

  • Shallow Copy (copy.copy() or list.copy()): Creates a new outer collection, but inserts references to the nested objects from the original. If a nested element is mutated, both copies reflect the change.
  • Deep Copy (copy.deepcopy()): Recursively duplicates the outer collection and every nested object inside it, creating a completely independent object graph.
python
import copy
 
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
 
original[0][0] = 999
print(shallow[0][0])  # 999 (affected!)
print(deep[0][0])     # 1 (completely isolated)

Q6: How do *args and **kwargs work in function definitions?

Answer:

  • *args allows a function to accept any number of positional arguments, which are collected into a tuple.
  • **kwargs allows a function to accept any number of keyword (named) arguments, which are collected into a dictionary.
python
def log_event(*args, **kwargs):
    print("Positional args:", args)
    print("Keyword args:", kwargs)
 
log_event(101, "login", user="Priya", ip="192.168.1.1")
# Positional args: (101, 'login')
# Keyword args: {'user': 'Priya', 'ip': '192.168.1.1'}

Q7: What are Generators and how does the yield keyword work?

Answer: A generator is a special type of iterator that produces values lazily on demand using the yield statement rather than computing them all up front in memory. When a generator encounters yield, it pauses execution, remembers its local state, and yields the value to the caller.

python
def read_large_log(file_path):
    with open(file_path, 'r') as f:
        for line in f:
            if "ERROR" in line:
                yield line.strip()
 
# Consumes virtually zero memory even for 50GB log files:
for error in read_large_log("production.log"):
    process(error)

Q8: What are Lambda Functions and when should you use them?

Answer: A lambda function is an anonymous, single-expression function defined with the lambda keyword: lambda arguments: expression. They can take any number of parameters but can only evaluate a single return expression.

They are ideal for short, disposable callbacks, such as custom sorting keys:

python
employees = [("Arjun", 75000), ("Meera", 92000), ("Rohan", 68000)]
# Sort by salary ascending:
employees.sort(key=lambda x: x[1])

Q9: Explain Python's LEGB Scope Rule.

Answer: When a variable name is referenced in Python, the interpreter searches for its value across four nested scopes in strict order:

  1. L (Local): Variables declared inside the currently executing function.
  2. E (Enclosing): Variables in enclosing functions (from inner to outer in nested functions/closures).
  3. G (Global): Variables declared at the module/file top level.
  4. B (Built-in): Pre-defined built-in names provided by Python (such as len, range, print).

Q10: How does the Dictionary .get() method differ from direct bracket lookup (dict[key])?

Answer: If the requested key does not exist in the dictionary:

  • dict[key] raises a fatal KeyError.
  • dict.get(key, default) returns None (or a specified default value) without raising an exception.
python
user_profile = {"name": "Priya", "role": "Data Analyst"}
 
# print(user_profile["department"]) -> Raises KeyError
dept = user_profile.get("department", "Unassigned")
print(dept)  # 'Unassigned'

Q11: What is a Decorator in Python?

Answer: A decorator is a design pattern that wraps a function, modifying or extending its behavior without changing its source code. In Python, decorators are higher-order functions that accept a function as input and return an updated wrapper function.

python
import time
 
def timer_decorator(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.time() - start:.4f}s")
        return result
    return wrapper
 
@timer_decorator
def process_data():
    time.sleep(0.5)
 
process_data()

Q12: How do you handle exceptions in Python using try, except, else, and finally?

Answer:

  • try: Contains code that might trigger an exception.
  • except: Catches and handles specific exception classes.
  • else: Executes only if no exception was raised in the try block.
  • finally: Guaranteed to execute regardless of whether an exception occurred, succeeded, or was caught (ideal for closing database handles).
python
try:
    num = int("100")
    result = 100 / num
except ValueError:
    print("Invalid conversion")
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print(f"Calculation succeeded: {result}")
finally:
    print("Cleanup completed")

Q13: What is the difference between break, continue, and pass?

Answer:

  • break: Immediately terminates the active loop and transfers execution to the statement immediately following the loop.
  • continue: Skips the remainder of the current loop iteration and jumps to the next evaluation cycle.
  • pass: A null statement used as a syntactic placeholder where code is required but no action is needed (e.g. empty classes or stubs).

Q14: How do Sets work and what is their time complexity for membership testing?

Answer: A set is an unordered, unindexed collection of unique, hashable elements. Because sets are implemented using hash tables internally, membership testing (x in my_set) operates in average $O(1)$ constant time, compared to $O(n)$ linear time in lists.

python
# Deduplicate a list instantly:
raw_ids = [101, 102, 101, 103, 104, 102]
unique_ids = list(set(raw_ids))

Q15: What is the Global Interpreter Lock (GIL)?

Answer: The GIL is a mutex (mutual exclusion lock) used by CPython to prevent multiple native OS threads from executing Python bytecode simultaneously on multiple CPU cores. It simplifies CPython's memory management (which uses reference counting). For CPU-bound parallel workloads, Python developers use multiprocessing instead of threading.


Q16: How does String Slicing work in Python?

Answer: The slicing syntax is sequence[start:stop:step].

  • start is inclusive (defaults to 0).
  • stop is exclusive (defaults to length).
  • step determines stride and direction.
python
s = "Topfolio"
print(s[0:3])    # 'Top'
print(s[3:])     # 'folio'
print(s[::2])    # 'Tpoi'
print(s[::-1])   # 'oilofpoT' (Reverse string)

Q17: What are __init__ and self in Python classes?

Answer:

  • __init__: The constructor method invoked automatically when a new instance of a class is created.
  • self: Represents the instance of the object itself, allowing methods to access and bind instance attributes and state.

Q18: What is the difference between append() and extend() in lists?

Answer:

  • .append(element): Appends the entire object as a single item at the end of the list.
  • .extend(iterable): Iterates over the argument and appends each individual element to the list.
python
a = [1, 2]
a.append([3, 4])
print(a)  # [1, 2, [3, 4]]
 
b = [1, 2]
b.extend([3, 4])
print(b)  # [1, 2, 3, 4]

Q19: How do you check if a key exists in a dictionary?

Answer: Use the in operator, which checks keys in $O(1)$ time:

python
if "email" in user_data:
    send_message(user_data["email"])

Q20: How does Python manage memory and perform garbage collection?

Answer: Python primarily manages memory using reference counting. Each object tracks how many references point to it; when reference count drops to 0, memory is immediately freed. To resolve circular references (e.g. Object A points to B, and B points to A), Python includes a secondary generational cyclic garbage collector that periodically inspects unreachable reference cycles.


Python Basic Interview Questions by Difficulty

Feature / Criteria

How to Prepare for Python Technical Screening Rounds

  1. Practice Whiteboard Coding Without Autocomplete: Interviewers frequently test on platforms without IDE syntax completion. Practice writing raw Python in simple text editors.
  2. Analyze Time & Space Complexity: For every function you write, state the Big-O complexity (e.g., "$O(n)$ time using a hash set for $O(1)$ lookups").
  3. Master Collections and Built-ins: Be fluent with collections.defaultdict, collections.Counter, and itertools.

For data-specific preparation, explore our Pandas Data Analysis Guide and practice with real datasets.


Practice Technical Interview Questions

Solve interactive coding and analytics questions in an in-browser sandbox with step-by-step guidance.

Start Interview Practice

Frequently Asked Questions

What are the most common Python basic interview questions?

The most common Python basic questions focus on mutable vs immutable types, list vs tuple differences, list comprehensions, dictionary operations, shallow vs deep copying, generators with yield, and error handling with try/except.

What is the difference between a list and a tuple in Python?

Lists are mutable (elements can be added, removed, or changed) and defined with square brackets []. Tuples are immutable (read-only after creation), defined with parentheses (), consume less memory, and can be used as dictionary keys.

What is the difference between '==' and 'is' in Python?

The '==' operator checks for value equality (do the two objects contain identical data?), whereas the 'is' operator checks for identity (do both variables reference the exact same memory address?).

Why do we use the 'with' statement in Python?

The 'with' statement implements context managers to guarantee proper resource acquisition and cleanup (such as automatically closing files or database connections), even if an unhandled exception is raised inside the block.

How do you reverse a string in Python without built-in functions?

You can reverse a string using extended slice indexing: reversed_str = text[::-1]. This steps through the string backwards from the end to the beginning.

Anuj Saini

Written by

Anuj SainiFounder & Lead Instructor

Founder at Topfolio with 6+ years in data & analytics across JPMC, Ultrahuman, and high-growth startups. Sat on hiring panels, reviewed 500+ resumes, and writes practical SQL & data guides.