Top 50 Python Interview Questions for Entry-Level Developers
Preparing for your first Python developer interview can feel overwhelming. Interviewers for entry-level roles typically focus on fundamentals: language semantics, built-in data structures, functions, object-oriented programming, and basic problem-solving. This tutorial walks you through the 50 most commonly asked Python interview questions, complete with explanations and runnable code examples. By the end, you'll understand what each concept is, why it matters, how to use it, and the best practices interviewers expect you to mention.
Why These Questions Matter
Entry-level interviews are less about exotic frameworks and more about whether you truly understand the language. A candidate who can explain the difference between a list and a tuple, or who knows when Python uses references versus copies, will stand out immediately. Mastering these questions demonstrates that you can write clean, idiomatic, and bug-free Python from day one.
Section 1: Python Basics (Questions 1β10)
1. What is Python and what are its key features?
Python is a high-level, interpreted, dynamically typed, and garbage-collected programming language. Key features include readable syntax, a large standard library, cross-platform support, and support for multiple paradigms (procedural, object-oriented, functional).
2. Is Python compiled or interpreted?
Python is technically both. Source code is first compiled into bytecode (stored in .pyc files) and then executed by the Python Virtual Machine. This hybrid approach gives Python portability while still being "interpreted" from the developer's perspective.
3. What is the difference between Python 2 and Python 3?
Python 3 introduced breaking changes: print became a function, strings are Unicode by default, integer division uses / for floats and // for integers, and several libraries were reorganized. Python 2 reached end-of-life in January 2020.
4. What are Python's built-in data types?
Python provides numeric types (int, float, complex), sequences (list, tuple, range), text (str), binary (bytes, bytearray), mappings (dict), sets (set, frozenset), and booleans (bool).
5. What is the difference between == and is?
== compares values for equality, while is compares object identity (memory address).
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True, same values
print(a is b) # False, different objects
6. What is PEP 8?
PEP 8 is Python's official style guide. It recommends 4-space indentation, lines under 79 characters, snake_case for functions and variables, PascalCase for classes, and imports on separate lines. Following PEP 8 signals professionalism.
7. How do you comment code in Python?
Single-line comments use #. Multi-line strings (triple quotes) can act as docstrings or block comments, though they are technically string literals.
# This is a single-line comment
"""
This is a multi-line string
often used as a docstring.
"""
def greet():
"""Return a friendly greeting."""
return "Hello"
8. What is a variable in Python and how is it typed?
Variables are names bound to objects. Python is dynamically typed, so you don't declare types. Type hints (introduced in PEP 484) allow optional annotations.
age: int = 25
name: str = "Alice"
9. What is the difference between / and //?
/ performs true division and always returns a float. // performs floor division and returns an int when both operands are ints.
print(7 / 2) # 3.5
print(7 // 2) # 3
print(-7 // 2) # -4 (floors toward negative infinity)
10. What are keywords in Python?
Keywords are reserved words that have special meaning, such as if, else, for, while, def, class, return, import, lambda, yield, and with. You cannot use them as identifiers.
Section 2: Data Types and Data Structures (Questions 11β20)
11. What is the difference between a list and a tuple?
Lists are mutable and use square brackets; tuples are immutable and use parentheses. Tuples are faster and can be used as dictionary keys.
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
my_list[0] = 10 # OK
# my_tuple[0] = 10 # Raises TypeError
12. What is a dictionary and how does it work?
A dictionary is an unordered (insertion-ordered since Python 3.7) collection of key-value pairs. It uses a hash table internally, giving O(1) average lookup, insertion, and deletion.
person = {"name": "Bob", "age": 30}
print(person["name"]) # Bob
print(person.get("email", "N/A")) # N/A
13. What is the difference between a set and a frozenset?
A set is mutable and unordered, holding unique elements. A frozenset is immutable and hashable, so it can be used as a dictionary key or set element.
14. How do you remove duplicates from a list?
The most idiomatic way is to convert to a set and back, though this loses order in older Python versions. To preserve order, use dict.fromkeys().
items = [1, 2, 2, 3, 3, 4]
unique = list(dict.fromkeys(items))
print(unique) # [1, 2, 3, 4]
15. What is list comprehension?
List comprehension is a concise way to create lists using a single expression. It is faster and more Pythonic than a for loop with append.
squares = [x * x for x in range(10) if x % 2 == 0]
print(squares) # [0, 4, 16, 36, 64]
16. What is the difference between append and extend?
append adds a single element to the end of a list. extend appends each element from an iterable.
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]
17. How do you sort a list in Python?
Use list.sort() for in-place sorting or sorted() to return a new sorted list. Both accept key and reverse arguments.
nums = [5, 2, 9, 1]
print(sorted(nums)) # [1, 2, 5, 9]
print(sorted(nums, reverse=True)) # [9, 5, 2, 1]
words = ["banana", "apple", "cherry"]
print(sorted(words, key=len)) # ['apple', 'banana', 'cherry']
18. What is slicing?
Slicing extracts a portion of a sequence using the syntax sequence[start:stop:step]. Omitting values uses defaults (start=0, stop=end, step=1).
s = "Python"
print(s[0:3]) # 'Pyt'
print(s[::-1]) # 'nohtyP' (reversed)
19. What is the difference between shallow copy and deep copy?
A shallow copy creates a new container but references the same nested objects. A deep copy recursively copies all nested objects.
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
shallow[0][0] = 99
print(original) # [[99, 2], [3, 4]] - affected!
deep[0][0] = 0
print(original) # [[99, 2], [3, 4]] - unaffected
20. How do you iterate over a dictionary?
You can iterate over keys, values, or both using .keys(), .values(), and .items().
d = {"a": 1, "b": 2}
for key, value in d.items():
print(f"{key}: {value}")
Section 3: Functions and Scope (Questions 21β28)
21. How do you define a function in Python?
Use the def keyword followed by the function name, parameters in parentheses, and a colon. The body is indented.
def add(a, b):
"""Return the sum of a and b."""
return a + b
print(add(3, 5)) # 8
22. What are default arguments?
Default arguments provide values when the caller omits them. Mutable defaults (like lists) are a common pitfall because they are evaluated once at definition time.
# Bad: mutable default
def append_to(item, lst=[]):
lst.append(item)
return lst
print(append_to(1)) # [1]
print(append_to(2)) # [1, 2] - shared list!
# Good: use None
def append_safe(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst
23. What are *args and **kwargs?
*args collects extra positional arguments as a tuple. **kwargs collects extra keyword arguments as a dictionary. They allow flexible function signatures.
def show(*args, **kwargs):
print("args:", args)
print("kwargs:", kwargs)
show(1, 2, 3, name="Alice", age=25)
# args: (1, 2, 3)
# kwargs: {'name': 'Alice', 'age': 25}
24. What is a lambda function?
A lambda is an anonymous, single-expression function. It is useful for short operations, often passed to map, filter, or sorted.
square = lambda x: x * x
print(square(5)) # 25
nums = [1, 2, 3]
doubled = list(map(lambda x: x * 2, nums))
print(doubled) # [2, 4, 6]
25. What is the difference between return and yield?
return sends a single value back and terminates the function. yield turns the function into a generator, producing values one at a time while preserving state.
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
for num in count_up_to(3):
print(num) # 1, 2, 3
26. What is scope in Python?
Python uses the LEGB rule: Local, Enclosing, Global, Built-in. Name resolution checks these scopes in order.
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x)
inner()
outer() # local
27. What do global and nonlocal do?
global lets you modify a module-level variable inside a function. nonlocal lets you modify a variable in the nearest enclosing scope (used in nested functions).
counter = 0
def increment():
global counter
counter += 1
def make_counter():
count = 0
def step():
nonlocal count
count += 1
return count
return step
28. What is a decorator?
A decorator is a function that takes another function and extends its behavior without modifying it. Decorators use the @ syntax.
def shout(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
@shout
def greet(name):
return f"hello {name}"
print(greet("alice")) # HELLO ALICE
Section 4: Object-Oriented Programming (Questions 29β36)
29. What is a class in Python?
A class is a blueprint for creating objects. It bundles data (attributes) and behavior (methods) together.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says woof!"
d = Dog("Rex")
print(d.bark()) # Rex says woof!
30. What is __init__?
__init__ is the constructor method. It runs automatically when an object is created and initializes instance attributes.
31. What is the difference between a class variable and an instance variable?
Class variables are shared across all instances. Instance variables are unique to each object.
class Cat:
species = "Felis catus" # class variable
def __init__(self, name):
self.name = name # instance variable
c1 = Cat("Mittens")
c2 = Cat("Whiskers")
print(c1.species, c2.species) # Felis catus Felis catus
print(c1.name, c2.name) # Mittens Whiskers
32. What is inheritance?
Inheritance lets a class derive properties and methods from another class, promoting code reuse.
class Animal:
def breathe(self):
return "breathing"
class Fish(Animal):
def swim(self):
return "swimming"
f = Fish()
print(f.breathe()) # breathing
print(f.swim()) # swimming
33. What is method overriding?
A subclass can redefine a method inherited from its parent to provide specialized behavior.
class Animal:
def sound(self):
return "some sound"
class Cat(Animal):
def sound(self):
return "meow"
34. What is super()?
super() calls a method from the parent class. It is commonly used inside __init__ to initialize the parent.
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, school):
super().__init__(name)
self.school = school
35. What are dunder methods?
Dunder (double underscore) methods like __str__, __repr__, __len__, and __eq__ let your objects integrate with Python's built-in functions and operators.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
def __eq__(self, other):
return self.x == other.x and self.y == other.y
print(Point(1, 2)) # Point(1, 2)
print(Point(1, 2) == Point(1, 2)) # True
36. What is the difference between __str__ and __repr__?
__str__ provides a human-readable string used by print. __repr__ provides an unambiguous representation useful for debugging, ideally a string that could recreate the object.
Section 5: Error Handling and File I/O (Questions 37β42)
37. How does exception handling work in Python?
Use try, except, else, and finally. The else block runs if no exception occurs; finally always runs.
try:
value = int(input("Enter a number: "))
except ValueError:
print("That's not a number")
else:
print(f"You entered {value}")
finally:
print("Done")
38. How do you raise an exception?
Use the raise keyword with an exception class or instance.
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
39. How do you create a custom exception?
Subclass Exception (or another built-in exception) to create a domain-specific error type.
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("Not enough money")
return balance - amount
40. How do you read a file in Python?
Use open() with a context manager (with) to ensure the file closes automatically.
with open("data.txt", "r") as f:
content = f.read()
print(content)
41. How do you write to a file?
Open the file in write ("w"), append ("a"), or exclusive-create ("x") mode.
with open("output.txt", "w") as f:
f.write("Hello, file!\n")
f.writelines(["Line 1\n", "Line 2\n"])
42. What is the difference between read, readline, and readlines?
read() returns the entire file as one string. readline() returns one line at a time. readlines() returns a list of all lines. For large files, iterate directly over the file object to save memory.
with open("data.txt") as f:
for line in f: # memory efficient
print(line.strip())
Section 6: Modules, Packages, and Standard Library (Questions 43β46)
43. What is the difference between a module and a package?
A module is a single .py file containing Python code. A package is a directory of modules with an __init__.py file (though this file is optional in modern Python with namespace packages).
44. How do you import modules?
Use import, from ... import ..., or import ... as .... Avoid wildcard imports (from module import *) because they pollute the namespace.
import math
from datetime import datetime
import numpy as np
print(math.pi)
print(datetime.now())
45. What is if __name__ == "__main__"?
This idiom checks whether a script is being run directly rather than imported. Code inside the block only executes when the file is the entry point.
def main():
print("Running")
if __name__ == "__main__":
main()
46. Name five useful standard library modules.
Common ones include os (operating system interface), sys (interpreter-related), json (JSON parsing), datetime (dates and times), collections (specialized containers like Counter and defaultdict), itertools, and re (regular expressions).
from collections import Counter
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
print(Counter(words)) # Counter({'apple': 3, 'banana': 2, 'cherry': 1})
Section 7: Advanced Concepts and Best Practices (Questions 47β50)
47. What is the difference between deepcopy and assignment?
Assignment creates a new reference to the same object. deepcopy creates a fully independent clone. This matters for nested structures, as shown in Question 19.
48. What is a virtual environment and why use one?
A virtual environment isolates project dependencies so different projects can use different package versions. Use venv (built-in) or virtualenv.
# Create and activate
python -m venv venv
source venv/bin/activate # macOS/Linux
venv\Scripts\activate # Windows
49. What is PEP and why is PEP 20 (The Zen of Python) important?
PEPs (Python Enhancement Proposals) describe proposed changes to Python. PEP 20, "The Zen of Python," captures Python's design philosophy. Run import this in a REPL to read it. Principles like "Simple is better than complex" and "Readability counts" guide idiomatic code.
50. What are some Python best practices every junior developer should follow?
- Follow PEP 8 for consistent style.
- Write meaningful names for variables and functions.
- Use list comprehensions instead of verbose loops where readable.
- Handle exceptions specifically, not with bare
except:. - Use context managers (
with) for files and locks. - Write docstrings and unit tests.
- Prefer returning values over printing inside functions.
- Use type hints for clarity in larger codebases.
- Keep functions small and focused on a single responsibility.
- Use virtual environments and a
requirements.txtfor reproducible setups.
Conclusion
Mastering these 50 questions gives you a strong foundation for any entry-level Python interview. The key is not just memorizing answers but understanding the reasoning behind each conceptβwhy tuples are immutable, why mutable default arguments are dangerous, why with statements matter, and why PEP 8 exists. Practice writing the code examples yourself, tweak them, break them, and fix them. Interviewers can quickly tell the difference between a candidate who has typed the code and one who has only read about it. Pair this knowledge with a small portfolio project or two, and you'll walk into your interview confident, prepared, and ready to demonstrate that you can write clean, idiomatic Python from day one.