Fresher Python Interview Questions

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

The main difference is that a list is mutable (you can change it) and a tuple is immutable (you cannot change it after creating it).

PointListTuple
Brackets[ ]( )
Can change itemsYesNo
Speed and memoryA little slower, uses more memoryA little faster, uses less memory
MethodsMany, like append() and remove()Only count() and index()
Use as dictionary keyNoYes, if it holds only immutable items
my_list = [1, 2, 3]
my_list[0] = 10
print(my_list)

my_tuple = (1, 2, 3)
my_tuple[0] = 10

Output:

Tutorials Class - Output Window

[10, 2, 3]
TypeError: 'tuple' object does not support item assignment

Use a list when the data will change, and a tuple when it should stay fixed. Read more about lists and tuples.

What are mutable and immutable types in Python?

A mutable object can be changed after it is created, and an immutable object cannot. When you “change” an immutable value, Python actually creates a new object.

MutableImmutable
list, dict, setint, float, bool, str, tuple, frozenset
numbers = [1, 2]
numbers.append(3)
print(numbers)

text = "hi"
print(text.upper())
print(text)

text[0] = "H"

Output:

Tutorials Class - Output Window

[1, 2, 3]
HI
hi
TypeError: 'str' object does not support item assignment

The list was changed in place, but the string stayed the same, and upper() gave a new string. This matters when you pass a list to a function, because the function can change the original list. See Python Data Types.

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

The == operator checks if two values are equal. The is operator checks if two names point to the same object in memory.

a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)
print(a is b)
print(a is c)

Output:

Tutorials Class - Output Window

True
False
True

a and b have the same values but are two separate lists. c is just another name for the same list as a. Use == to compare values, and use is mainly for None, like if x is None:. See Python Operators.

What are *args and **kwargs in Python?

*args lets a function accept any number of positional arguments, which arrive as a tuple. **kwargs lets it accept any number of keyword arguments (name=value), which arrive as a dictionary.

def show(*args, **kwargs):
    print(args)
    print(kwargs)

show(1, 2, name="Robin", age=20)

Output:

Tutorials Class - Output Window

(1, 2)
{'name': 'Robin', 'age': 20}

The names args and kwargs are only a habit. The stars are what matter. They are useful when you do not know in advance how many values will be passed, for example in a function that adds any amount of numbers.

def total(*numbers):
    return sum(numbers)

print(total(1, 2, 3, 4))

Output:

Tutorials Class - Output Window

10

What is list comprehension in Python?

List comprehension is a short way to create a new list in a single line. The syntax is [expression for item in iterable if condition].

squares = [x * x for x in range(1, 6)]
print(squares)

evens = [x for x in range(10) if x % 2 == 0]
print(evens)

Output:

Tutorials Class - Output Window

[1, 4, 9, 16, 25]
[0, 2, 4, 6, 8]

The same work with a normal loop needs three or four lines:

squares = []
for x in range(1, 6):
    squares.append(x * x)

Comprehensions are shorter and usually a bit faster, but keep them simple. If the line becomes hard to read, use a normal loop. Python also has dictionary and set comprehensions. See Python for loop.

How does exception handling work in Python?

Python handles errors with the try and except blocks. The risky code goes in try, and if an error happens, the matching except block runs instead of the program crashing.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print(result)
finally:
    print("Done")

Output:

Tutorials Class - Output Window

Cannot divide by zero
Done

  • try: the code that may raise an error.
  • except: runs if that error happens. You can have more than one.
  • else: runs only if no error happened.
  • finally: always runs, good for cleanup like closing a file.

Catch the specific error you expect, not every error. You can also raise your own error with raise. See Python Errors.

What is the __init__() method in Python?

__init__() is a special method of a class that runs automatically when a new object is created. It is used to set the starting values of the object, so it works like a constructor in other languages.

class Car:
    def __init__(self, brand, year):
        self.brand = brand
        self.year = year

car = Car("Tata", 2024)
print(car.brand)
print(car.year)

Output:

Tutorials Class - Output Window

Tata
2024

The first parameter is always self. The other values come from the call Car("Tata", 2024). Technically the object is created by __new__() first and then __init__() sets it up, but you rarely write __new__() yourself. See Python Classes and Objects.

What is inheritance in Python?

Inheritance lets a new class (child) take the attributes and methods of an existing class (parent). It helps to reuse code, and the child can also change or add its own behaviour.

class Animal:
    def speak(self):
        print("Some sound")

class Dog(Animal):
    def speak(self):
        print("Bark")

class Cat(Animal):
    pass

Dog().speak()
Cat().speak()

Output:

Tutorials Class - Output Window

Bark
Some sound

Dog replaces (overrides) the speak() method, while Cat uses the one from Animal. Use super() to call a method of the parent class. Python supports single, multiple, multilevel, hierarchical and hybrid inheritance. See Python OOPS Introduction.

What is the difference between a module and a package in Python?

A module is a single Python file (.py) that has functions, classes or variables. A package is a folder that groups related modules together.

import math
print(math.sqrt(16))

from math import pi
print(pi)

Output:

Tutorials Class - Output Window

4.0
3.141592653589793

A package looks like this on disk:

shop/
    __init__.py
    cart.py
    payment.py
from shop import cart
from shop.payment import pay

The __init__.py file marks the folder as a regular package. Python can also use folders without it, but most projects still keep the file. Python comes with many built-in modules, and you can install more with pip.

What is a virtual environment in Python?

A virtual environment is an isolated folder that has its own Python packages for one project. It stops different projects from clashing, for example when one needs version 1 of a library and another needs version 2.

Create and use it with these commands. The first command is the same everywhere.

python -m venv venv

Activate it on macOS or Linux:

source venv/bin/activate

Activate it on Windows:

venv\Scripts\activate

Now install packages with pip, the Python package installer. They go only into this environment.

pip install requests
pip freeze > requirements.txt
pip install -r requirements.txt

pip freeze saves the list of installed packages, and the last command installs them again on another computer. Type deactivate to leave the environment.

What are f-strings in Python?

An f-string (formatted string) is a string that starts with f and can hold variables and expressions inside curly braces { }. They were added in Python 3.6 and are the easiest way to format text.

name = "Robin"
age = 20
price = 49.5

print(f"{name} is {age} years old")
print(f"Next year: {age + 1}")
print(f"Total: {price:.2f}")

Output:

Tutorials Class - Output Window

Robin is 20 years old
Next year: 21
Total: 49.50

:.2f shows the number with two digits after the decimal point. F-strings are shorter and easier to read than the older % formatting or format().