Python Interview Questions for Freshers: Basics (2027)

50 Python interview questions for freshers with answers and code: data types, mutability, lists vs tuples, functions, scope, exceptions, OOP, coding tasks.

Sep 5, 2025 - 17:26
Nov 7, 2026 - 07:56
 0  79
Python Interview Questions for Freshers: Basics (2027)

Python interview questions for freshers check the basics: data types, mutability, lists versus tuples, dictionaries and sets, functions and arguments, scope, exceptions, files, modules, classes and a few short coding tasks. Interviewers want correct, simple answers and small working code, not framework knowledge. Most rounds also ask you to predict the output of a short snippet. This page has 50 questions with answers and code, grouped by level.

Language details were checked against the official Python documentation at docs.python.org in November 2026, using Python 3 behaviour throughout. This page is for freshers and career switchers. If you are applying for DevOps roles with some experience, our scenario-based Python interview questions for DevOps is the main guide in this series, and the 150+ Python interview questions for DevOps covers boto3, pytest and asyncio.

Key takeaways

  • Know which built-in types are mutable (list, dict, set) and which are immutable (int, float, str, tuple, frozenset). Many trick questions come from this.
  • Default argument values are evaluated once, when the function is defined. A mutable default such as [] is shared between calls.
  • is compares identity; == compares value. Use is only for None and similar singletons.
  • Explain Python's scope rule as LEGB: local, enclosing, global, built-in.
  • Practise five small programs by hand: reverse a string, count words, find duplicates, check a palindrome and FizzBuzz.
  • Python 2 reached end of life on 1 January 2020. Answer in Python 3 unless told otherwise.

How the Python interview pages differ

PageBest for
This pageFreshers: language basics and output-prediction questions
Scenario-based Python for DevOpsReal automation tasks with subprocess, requests and logs
Python coding questions with solutionsAlgorithm rounds: hash maps, sliding window, heaps
150+ Python questions for DevOpsBroad coverage up to senior level

Basic Python questions

1. What is Python?

Python is a high-level, general-purpose programming language with dynamic typing and automatic memory management. Code is compiled to bytecode and run by an interpreter; the reference implementation is CPython. It is used for automation, web back ends, data work and testing.

2. Is Python compiled or interpreted?

Both, in a sense. CPython compiles source to bytecode (stored in .pyc files in __pycache__) and then a virtual machine interprets the bytecode. In interviews, "interpreted with a bytecode compilation step" is a safe answer.

3. What does dynamic typing mean?

Variables do not have fixed types; values do. The same name can refer to an int and later a string. Type hints (def f(x: int) -> str) are optional and not enforced at runtime; tools such as mypy check them.

4. Why does indentation matter in Python?

Indentation defines code blocks. A wrong indent changes which statements belong to an if, loop or function, or raises an IndentationError. PEP 8 recommends four spaces per level.

5. What is PEP 8?

The style guide for Python code: naming (snake_case for functions and variables, CapWords for classes), four-space indentation, line length, imports at the top, and spacing. Tools such as flake8, pylint and ruff check it.

6. What are the main built-in data types?

CategoryTypesMutable?
Numbersint, float, complex, boolNo
TextstrNo
Sequenceslist, tuple, rangelist yes; tuple and range no
MappingdictYes
Setsset, frozensetset yes; frozenset no
Binarybytes, bytearraybytes no; bytearray yes
NoneNoneTypeNo

7. What is the difference between a list and a tuple?

A list is mutable: you can add, remove and change items. A tuple is immutable once created. Tuples can be dictionary keys if their items are hashable, and they signal "fixed record" to the reader, such as (host, port).

8. What is the output?

a = [1, 2, 3]
b = a
b.append(4)
print(a)

[1, 2, 3, 4]. Assignment does not copy; a and b are two names for the same list. Use a.copy(), list(a) or a[:] for a shallow copy.

9. What is the difference between a shallow copy and a deep copy?

A shallow copy creates a new outer object but keeps references to the same inner objects. A deep copy, from copy.deepcopy(), copies inner objects recursively. It matters for nested lists and dictionaries.

10. What is the difference between is and ==?

== checks whether values are equal. is checks whether two names refer to the same object. Write if x is None, but compare strings and numbers with ==.

11. How do you take user input and convert it to a number?

input() always returns a string, so convert it: age = int(input("Age: ")). Wrap it in try/except ValueError if the input may not be a number.

12. What is slicing?

Taking part of a sequence with seq[start:stop:step]. stop is excluded. s[::-1] reverses a string or list, and s[-1] is the last item.

13. What are f-strings?

String literals prefixed with f that evaluate expressions inside braces: f"{name} has {count} items". They are the usual way to format strings in modern Python.

14. What does None mean?

The single value of NoneType, used for "no value". A function without a return statement returns None.

15. What are truthy and falsy values?

Values that count as false in a condition: False, None, zero of any numeric type, and empty containers ("", [], {}, set()). Almost everything else counts as true.

Data structure questions

16. How do you remove duplicates from a list while keeping order?

items = [3, 1, 3, 2, 1]
unique = list(dict.fromkeys(items))
print(unique)  # [3, 1, 2]

Dictionaries keep insertion order (guaranteed since Python 3.7). list(set(items)) also removes duplicates but does not keep order.

17. How do you safely read a key that may not exist in a dictionary?

Use d.get("key"), which returns None, or d.get("key", default). d["key"] raises KeyError if the key is missing.

18. How do you loop over keys and values of a dictionary?

ports = {"http": 80, "https": 443}
for name, port in ports.items():
    print(name, port)

19. What can be a dictionary key?

Any hashable object: strings, numbers, tuples of hashable items, frozensets. Lists and dictionaries cannot be keys because they are mutable and unhashable.

20. What is a set used for?

Storing unique items with fast membership tests, and set algebra: union (|), intersection (&), difference (-). Example: finding which servers appear in both of two lists.

21. What is a list comprehension?

A compact way to build a list: [x * x for x in range(10) if x % 2 == 0]. There are also dictionary and set comprehensions, and generator expressions with parentheses.

22. How do you count word frequency in a string?

from collections import Counter

text = "error warn error info error"
counts = Counter(text.split())
print(counts.most_common(1))  # [('error', 3)]

23. What is the difference between append() and extend()?

append(x) adds x as one item. extend(iterable) adds each item of the iterable. [1].append([2, 3]) gives [1, [2, 3]]; extend gives [1, 2, 3].

24. How do you sort a list of dictionaries by a field?

sorted(users, key=lambda u: u["age"]). sorted() returns a new list; list.sort() sorts in place and returns None.

Functions and scope questions

25. What are *args and **kwargs?

*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary. The names are conventions; the stars do the work.

26. What is wrong with this function?

def add_item(item, bucket=[]):
    bucket.append(item)
    return bucket

print(add_item(1))
print(add_item(2))

It prints [1] then [1, 2], because the default list is created once when the function is defined and reused. Use bucket=None and create a new list inside the function when it is None.

27. What is the LEGB rule?

The order Python searches for a name: Local (inside the function), Enclosing (outer functions), Global (module level), Built-in. Assigning to a global name inside a function needs the global statement, and to an enclosing function's name needs nonlocal.

28. What is a lambda?

A small anonymous function written as one expression: lambda x: x * 2. It is useful as a key for sorting or in map and filter. Use def for anything longer.

29. Does Python pass arguments by value or by reference?

Neither exactly. Python passes references to objects ("call by object reference" or "call by sharing"). A function can change a mutable object it receives, but reassigning the parameter name does not affect the caller.

30. What is a docstring?

A string literal as the first statement of a module, function or class that documents it. It is available as __doc__ and shown by help().

31. What does if __name__ == "__main__": do?

The block runs only when the file is executed directly, not when it is imported as a module. It keeps script code separate from reusable functions.

32. What is a generator?

A function that uses yield to produce values one at a time. It keeps its state between values and uses little memory, which helps when reading large files line by line.

def read_errors(path):
    with open(path) as f:
        for line in f:
            if "ERROR" in line:
                yield line.rstrip()

33. What is a decorator?

A function that takes a function and returns a new function, applied with the @name syntax above a definition. It is used for logging, timing, retries and access checks without changing the wrapped function's code.

Errors, files and modules

34. How does exception handling work?

try holds code that may fail, except handles specific exceptions, else runs if no exception happened, and finally always runs. Catch specific exceptions such as FileNotFoundError rather than a bare except:.

try:
    with open("config.txt") as f:
        data = f.read()
except FileNotFoundError:
    data = ""
finally:
    print("done")

35. How do you raise your own exception?

Use raise ValueError("port must be between 1 and 65535"). For custom errors, define a class that inherits from Exception.

36. Why use with open(...)?

The with statement uses a context manager that closes the file automatically, even if an exception occurs. Without it you must call close() yourself.

37. What file modes should you know?

"r" read (default), "w" write and truncate, "a" append, "x" create and fail if it exists, plus "b" for binary and "+" for read and write.

38. What is the difference between a module and a package?

A module is a single .py file. A package is a directory of modules that can be imported with dotted names, traditionally with an __init__.py file.

39. What is pip and what is a virtual environment?

pip installs packages from the Python Package Index. A virtual environment, created with python -m venv .venv, gives a project its own interpreter and packages so projects do not conflict. Pin versions in a requirements.txt or pyproject.toml.

Object-oriented basics

40. What are a class and an object?

A class is a blueprint that defines attributes and methods. An object is an instance created from it. __init__ sets up a new instance, and self refers to that instance.

class Server:
    def __init__(self, name, port=22):
        self.name = name
        self.port = port

    def address(self):
        return f"{self.name}:{self.port}"

web = Server("web01", 8080)
print(web.address())  # web01:8080

41. What is inheritance?

A class can inherit attributes and methods from a parent class and override them. super() calls the parent's version, often inside __init__.

42. What is the difference between a class attribute and an instance attribute?

A class attribute is defined on the class and shared by all instances. An instance attribute is set on self and belongs to one object.

43. What are @staticmethod and @classmethod?

A static method does not receive the instance or class; it is a function grouped with the class. A class method receives the class as cls and is often used for alternative constructors such as from_dict().

44. What do __str__ and __repr__ do?

__str__ returns a readable string for users and print(). __repr__ returns an unambiguous string for developers, ideally one that could recreate the object.

45. What is the GIL?

The Global Interpreter Lock in CPython lets only one thread execute Python bytecode at a time, so threads help with waiting on I/O more than with CPU work. Use multiprocessing for CPU-bound tasks. Python 3.13 added an experimental free-threaded build without the GIL, and Python 3.14 made the free-threaded build officially supported, though it is still a separate build and not the default.

Scenario round: short coding tasks freshers get

46. Reverse a string without slicing.

def reverse(s):
    return "".join(reversed(s))

47. Check whether a string is a palindrome, ignoring case and spaces.

def is_palindrome(s):
    cleaned = "".join(ch.lower() for ch in s if ch.isalnum())
    return cleaned == cleaned[::-1]

print(is_palindrome("Never odd or even"))  # True

48. Write FizzBuzz for 1 to 15.

for n in range(1, 16):
    if n % 15 == 0:
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)

49. Find the second largest number in a list.

def second_largest(nums):
    unique = sorted(set(nums))
    return unique[-2] if len(unique) >= 2 else None

print(second_largest([4, 9, 9, 2]))  # 4

50. Count lines containing "ERROR" in a log file.

def count_errors(path):
    with open(path) as f:
        return sum(1 for line in f if "ERROR" in line)

This version reads the file line by line, so it works on large logs. It is a common first task in DevOps-flavoured fresher rounds.

How to prepare in two weeks

  • Days 1 to 4: types, strings, lists, dictionaries and sets. Type every example above and change it.
  • Days 5 to 8: functions, scope, exceptions, files and modules. Write one small script per day.
  • Days 9 to 11: classes and inheritance, then predict-the-output exercises.
  • Days 12 to 14: timed coding tasks and a mock interview where you explain your code aloud.

If you want to apply Python in DevOps work, read top 10 Python scripts for DevOps automation and 15 DevOps task automations using Python. Our DevOps training uses Python and shell scripting for automation labs, in the Kharadi, Pune classroom and live online across India.

Frequently asked questions

What Python questions are asked to freshers?

Data types, lists versus tuples, dictionaries, mutability, functions and arguments, scope, exceptions, file handling, classes and short coding tasks.

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

Lists are mutable; tuples are immutable and can be dictionary keys when their items are hashable.

Why is a mutable default argument a problem?

The default is created once at definition time, so changes persist between calls. Use None and create the object inside.

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

is checks identity; == checks equality of values.

Is Python interpreted or compiled?

CPython compiles source code to bytecode, which its virtual machine then interprets.

What is the GIL in Python?

A lock in CPython that lets one thread run Python bytecode at a time. Free-threaded builds without it exist from Python 3.13.

Should freshers learn Python 2?

No. Python 2 reached end of life on 1 January 2020. Learn and answer in Python 3.

Official references

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.