75+ Python Interview Questions and Answers for 2025

Hey there, future Python rockstar! Preparing for a Python interview can feel like gearing up for a big adventure. Whether you’re aiming for a data science role, a backend developer gig, or just want to flex your Python skills, this article is your trusty guide. Python’s versatility – think AI, web dev, automation – makes it a must-know language, and nailing those interview questions is the key to landing your dream job.

In this article, I’ll walk you through 75+ Python interview questions, complete with code examples, explanations, and a friendly tone to keep things engaging. From beginner basics to advanced concepts, we’ve got you covered. Let’s dive in and get you interview-ready!

Table of Contents

Python Interview Questions

This guide is packed with practical Python coding questions and answers, perfect for freshers and seasoned coders alike. We’ll cover everything from strings and lists to NumPy, pandas, and OOP. Each question comes with a clear explanation and code to help you understand why things work the way they do. Ready? Let’s go!

Python Interview Questions for Freshers

How do you convert a string to an integer in Python?

You can use the int() function to convert a string to an integer.

Explanation: The int() function takes a string that represents a valid integer (like “42”) and converts it to an integer. Be careful—if the string isn’t a valid number (e.g., “abc”), you’ll get a ValueError.

Here’s a quick example:

# Converting string to int
num_str = "42"
num_int = int(num_str)
print(num_int)  # Output: 42
print(type(num_int))  # Output: <class 'int'>

Write a code snippet to split a string into a list.

The split() method is your go-to for turning a string into a list based on a delimiter (like a space or comma).

Explanation: The split(” “) method breaks the string at every space, creating a list of words. You can use other delimiters, like split(“,”) for comma-separated strings.

# Splitting a string into a list
sentence = "Python is awesome"
word_list = sentence.split(" ")
print(word_list)  # Output: ['Python', 'is', 'awesome']

How can you reverse a string in Python?

Use slicing with a step of -1 to reverse a string.

Explanation: The slice [::-1] means “take all characters, stepping backward.” It’s a concise way to reverse strings without loops.

# Reversing a string
text = "FunWithAI"
reversed_text = text[::-1]
print(reversed_text)  # Output: IAHtiWnuF

Write a code snippet to sort a list in ascending order.

Use sort() or sorted() to sort a list.

Explanation: sort() modifies the list in place, while sorted() creates a new list. Use reverse=True for descending order.

# Sorting a list
numbers = [7, 3, 9, 1, 5]
numbers.sort()
print(numbers)  # Output: [1, 3, 5, 7, 9]

# Using sorted() (returns new list)
numbers = [7, 3, 9, 1, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # Output: [1, 3, 5, 7, 9]

What’s the difference between mutable and immutable objects in Python?

Mutable objects: Can be modified after creation (e.g., lists, dictionaries).

Immutable objects: Cannot be changed once created (e.g., strings, tuples).

Explanation: Mutable objects allow in-place changes, while immutable objects require creating a new object. This impacts performance and memory.

Example:

# Mutable (list)
my_list = [1, 2, 3]
my_list[0] = 99
print(my_list)  # Output: [99, 2, 3]

# Immutable (string)
my_string = "FunWithAI"
my_string[0] = "f"  # Raises TypeError

How do you delete a file in Python?

Use os.remove() from the os module.

Explanation: os.remove() deletes the specified file. Check if the file exists with os.path.exists() to avoid errors.

import os
file_name = "temp.txt"
if os.path.exists(file_name):
    os.remove(file_name)
    print(f"{file_name} deleted successfully")
else:
    print("File not found")

How do you access elements in a list?

Use indexing (0-based) or negative indexing (from the end).

Explanation: Positive indices access elements from the start, negative indices from the end. Invalid indices raise an IndexError.

# Accessing list elements
fruits = ["apple", "banana", "cherry"]
print(fruits[1])  # Output: banana
print(fruits[-1])  # Output: cherry

What are the ways to delete elements from a list?

Use remove(), pop(), or del.

Explanation:
remove() deletes the first occurrence of a value.
pop() removes and returns an element by index (defaults to the last element).
del removes by index or slice.

# Using remove() (by value)
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)  # Output: ['apple', 'cherry']

# Using pop() (by index, returns element)
fruits = ["apple", "banana", "cherry"]
popped = fruits.pop(1)
print(fruits)  # Output: ['apple', 'cherry']
print(popped)  # Output: banana

# Using del (by index)
fruits = ["apple", "banana", "cherry"]
del fruits[1]
print(fruits)  # Output: ['apple', 'cherry']

How do you delete an entire list in Python?

Use the clear() method or del.

Explanation: clear() empties the list but keeps the object, while del removes the list entirely.

# Using clear()
my_list = [1, 2, 3]
my_list.clear()
print(my_list)  # Output: []

# Using del
my_list = [1, 2, 3]
del my_list
# print(my_list)  # Raises NameError: name 'my_list' is not defined

How do you reverse an array in Python?

Use NumPy’s flip() or slicing.

Explanation: np.flip() reverses the array, while [::-1] uses slicing for the same effect. Both work efficiently with NumPy arrays.

import numpy as np

# Using flip()
arr = np.array([1, 2, 3, 4])
reversed_arr = np.flip(arr)
print(reversed_arr)  # Output: [4 3 2 1]

# Using slicing
arr = np.array([1, 2, 3, 4])
reversed_arr = arr[::-1]
print(reversed_arr)  # Output: [4 3 2 1]

How do you get, delete, and update elements in an array?

Use indexing for access/update and np.delete() for deletion.

Explanation:
Access/update via index (e.g., arr[1]).
np.delete() removes an element at the specified index, returning a new array.

import numpy as np

# Creating an array
arr = np.array([10, 20, 30, 40])

# Access
print(arr[1])  # Output: 20

# Update
arr[1] = 99
print(arr)  # Output: [10 99 30 40]

# Delete
arr = np.delete(arr, 1)
print(arr)  # Output: [10 30 40]

How do you concatenate two lists in Python?

Use +, extend(), or list comprehension with zip() for special cases.

Explanation: + creates a new list, extend() modifies the first list, and zip() pairs elements for custom concatenation.

# Using +
list1 = [1, 2]
list2 = [3, 4]
combined = list1 + list2
print(combined)  # Output: [1, 2, 3, 4]

# Using extend()
list1 = [1, 2]
list2 = [3, 4]
list1.extend(list2)
print(list1)  # Output: [1, 2, 3, 4]

# Using zip() for pairwise concatenation
list1 = ['a', 'b']
list2 = ['1', '2']
combined = [x + y for x, y in zip(list1, list2)]
print(combined)  # Output: ['a1', 'b2']

How do you square every element in a list?

Use a loop or list comprehension.

Explanation: List comprehension is concise and Pythonic, but a loop is more explicit. Both multiply each element by itself.

# Using list comprehension
numbers = [1, 2, 3, 4]
squares = [x * x for x in numbers]
print(squares)  # Output: [1, 4, 9, 16]

# Using a loop
squares = []
for x in numbers:
    squares.append(x * x)
print(squares)  # Output: [1, 4, 9, 16]

What’s the difference between range() and xrange()?

In Python 2, range() returns a list, while xrange() returns an iterator (more memory-efficient).
In Python 3, xrange() is gone, and range() behaves like Python 2’s xrange(), returning an iterator.

Explanation: Python 3’s range() is memory-efficient, generating values on demand.

for i in range(5):
    print(i)  # Output: 0 1 2 3 4

What are pickling and unpickling in Python?

Pickling: Converting a Python object (e.g., list, dict) to a byte stream.
Unpickling: Converting a byte stream back to a Python object.

Explanation: The pickle module serializes objects for storage or transfer. Use ‘wb’ for writing and ‘rb’ for reading binary files.

import pickle

# Pickling
data = {'name': 'Alice', 'age': 25}
with open('data.pkl', 'wb') as f:
    pickle.dump(data, f)

# Unpickling
with open('data.pkl', 'rb') as f:
    loaded_data = pickle.load(f)
print(loaded_data)  # Output: {'name': 'Alice', 'age': 25}

What is __init__ in Python?

__init__ is a special method (constructor) used to initialize a class instance.

Explanation: __init__ runs automatically when an object is created, setting initial attributes. It’s like setting up a new character in a game.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("Alice", 25)
print(person.name, person.age)  # Output: Alice 25

What is PEP-8?

PEP-8 is Python’s style guide for writing readable, consistent code.

Key Rules:
Use 4 spaces for indentation.
Keep lines under 79 characters.
Use snake_case for variables/functions, CamelCase for classes.

Explanation: PEP-8 ensures your code is clean and team-friendly. Tools like flake8 can check compliance.

# PEP-8 compliant
def calculate_sum(a, b):
    result = a + b
    return result

Are NumPy arrays faster than Python lists? Why?

Yes, NumPy arrays are faster than Python lists for numerical operations.

Reasons:
NumPy uses fixed-type, contiguous memory (faster access).
Operations are implemented in optimized C code.
Lists are flexible but slower due to dynamic typing and overhead.

Explanation: NumPy’s vectorized operations are much faster than list loops.

import numpy as np
import time

# List vs. NumPy
lst = list(range(1000000))
arr = np.arange(1000000)

start = time.time()
lst = [x * 2 for x in lst]
print("List time:", time.time() - start)

start = time.time()
arr = arr * 2
print("NumPy time:", time.time() - start)

What’s the difference between a list and a tuple?

Answer:
List: Mutable, defined with [], slower, more methods.
Tuple: Immutable, defined with (), faster, fewer methods.

Explanation: Use tuples for fixed data (e.g., dictionary keys) and lists for dynamic data.

# List
my_list = [1, 2, 3]
my_list[0] = 99
print(my_list)  # Output: [99, 2, 3]

# Tuple
my_tuple = (1, 2, 3)
# my_tuple[0] = 99  # Raises TypeError

What are Python sets and their properties?

A set is an unordered collection of unique elements.
Properties:
Unordered: No indexing/slicing.
Unique: No duplicates.
Mutable: Add/remove elements.
Unhashable: Cannot be dictionary keys (use frozenset for that).

Explanation: Sets are great for membership tests and removing duplicates.

my_set = {1, 2, 2, 3}
print(my_set)  # Output: {1, 2, 3}
my_set.add(4)
print(my_set)  # Output: {1, 2, 3, 4}

What’s the difference between split() and join()?

split(): Breaks a string into a list based on a delimiter.
join(): Combines a list of strings into a single string with a delimiter.

Explanation: split() is the opposite of join(). Use them for string-to-list and list-to-string conversions.

# Split
text = "Python,Fun,AI"
words = text.split(",")
print(words)  # Output: ['Python', 'Fun', 'AI']

# Join
delimiter = ","
new_text = delimiter.join(words)
print(new_text)  # Output: Python,Fun,AI

What are Python’s logical operators?

Python has three logical operators: and, or, not.

Explanation:
and: True if both operands are True.
or: True if at least one operand is True.
not: Inverts the boolean value.

a, b = True, False
print(a and b)  # Output: False
print(a or b)   # Output: True
print(not a)    # Output: False

What are the top 5 Python string functions?

len(): Returns string length.
strip(): Removes leading/trailing whitespace.
replace(): Replaces substrings.
split(): Splits string into a list.
upper()/lower(): Converts case.

Explanation: These methods are essential for string manipulation.

text = "  FunWithAI!  "
print(len(text))          # Output: 13
print(text.strip())       # Output: FunWithAI!
print(text.replace("AI", "Python"))  # Output:   FunWithPython!
print(text.split("!"))    # Output: ['  FunWithAI', '  ']
print(text.upper())       # Output:   FUNWITHAI!  

What is the pass keyword in Python?

pass is a placeholder that does nothing, used when syntax requires a statement.

Explanation: Use pass in empty functions, loops, or classes to avoid syntax errors.

def my_function():
    pass  # TODO: Implement later

What is the continue keyword in Python?

continue skips the current loop iteration and moves to the next.

Explanation: When i == 2, continue skips printing and proceeds to the next iteration.

for i in range(5):
    if i == 2:
        continue
    print(i)  # Output: 0 1 3 4

What are mutable vs. immutable data types?

Mutable: Can be modified (e.g., lists, dictionaries, sets).
Immutable: Cannot be modified (e.g., strings, tuples, integers).

Explanation: Immutable types are safer for fixed data but require new objects for changes.

# Mutable
my_list = [1, 2]
my_list.append(3)
print(my_list)  # Output: [1, 2, 3]

# Immutable
my_tuple = (1, 2)
# my_tuple[0] = 99  # Raises TypeError

What is the try and except block in Python?

try and except handle exceptions to prevent crashes.

Explanation: Code in try runs, and if an exception occurs, except handles it. Use specific exceptions for better control.

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

What are Python functions, and how do they optimize code?

Functions are reusable code blocks that perform specific tasks.

Optimization Benefits:
Reusability: Call functions multiple times.
Readability: Break code into logical chunks.
Testing: Isolate and test functionality.
Performance: Use optimized libraries or logic.
Explanation: Functions reduce redundancy and improve maintainability.

def add(a, b):
    return a + b

print(add(2, 3))  # Output: 5

Why is NumPy popular in data science?

NumPy is a cornerstone for numerical computing.

Reasons:
Speed: Uses C-based operations.
Arrays: Efficient for large datasets.
Functions: Rich mathematical/statistical tools.
Integration: Works with pandas, SciPy, etc.

Explanation: NumPy’s arrays and functions make data processing fast and easy.

import numpy as np
arr = np.array([1, 2, 3])
print(np.mean(arr))  # Output: 2.0

What are list and dict comprehensions?

List comprehension: Concise way to create lists.
Dict comprehension: Concise way to create dictionaries.

Explanation: Comprehensions are Pythonic and reduce boilerplate code.

# List comprehension
squares = [x**2 for x in range(5)]
print(squares)  # Output: [0, 1, 4, 9, 16]

# Dict comprehension
square_dict = {x: x**2 for x in range(5)}
print(square_dict)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

What are global and local variables?

Global: Defined outside functions, accessible everywhere.
Local: Defined inside functions, accessible only within.

Explanation: Local variables take precedence in their scope. Use global keyword to modify globals inside functions.

x = 10  # Global
def my_func():
    x = 5  # Local
    print(x)  # Output: 5
my_func()
print(x)  # Output: 10

What is an OrderedDict?

OrderedDict (from collections) is a dictionary that remembers insertion order.

Explanation: Unlike regular dictionaries (ordered since Python 3.7), OrderedDict offers explicit order control.

from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
print(od)  # Output: OrderedDict([('a', 1), ('b', 2)])

What’s the difference between return and yield?

return: Exits a function and sends a value.
yield: Produces a value in a generator, pausing execution.

Explanation: yield makes functions memory-efficient for large sequences.

def my_generator():
    yield 1
    yield 2
    yield 3

gen = my_generator()
print(next(gen))  # Output: 1
print(next(gen))  # Output: 2

What are lambda functions, and why are they useful?

Lambda functions are anonymous, single-expression functions.

Use Cases:
Short, throwaway functions.
Used with map(), filter(), etc.
Explanation: Lambdas are concise for simple tasks but less readable for complex logic.

# Lambda to square a number
square = lambda x: x**2
print(square(5))  # Output: 25

What is the assert keyword?

assert tests a condition, raising AssertionError if False.

Explanation: Use assert for debugging, not production error handling.

x = 5
assert x > 0, "x must be positive"
# assert x < 0  # Raises AssertionError

What are decorators in Python?

Decorators modify or extend a function/class without changing its code.

Explanation: Decorators wrap functions for logging, timing, etc.

def my_decorator(func):
    def wrapper():
        print("Before function")
        func()
        print("After function")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
# Output:
# Before function
# Hello!
# After function

What are Python’s built-in data types?

None Type: None
Numeric: int, float, complex, bool
Sequence: list, tuple, range, str
Mapping: dict
Set: set, frozenset
Explanation: These types cover most data needs.

What’s the difference between set and frozenset?

Set: Mutable, can add/remove elements.
Frozenset: Immutable, cannot be modified.

Explanation: Use frozenset for hashable, immutable sets (e.g., dictionary keys).

my_set = {1, 2}
my_set.add(3)
print(my_set)  # Output: {1, 2, 3}

my_frozenset = frozenset([1, 2])
# my_frozenset.add(3)  # Raises AttributeError

When should you use a tuple instead of a list?

Use tuples for:
Immutable data (safer).
Dictionary keys (hashable).
Faster performance (less overhead).

Explanation: Tuples are lightweight and secure for fixed data.

my_tuple = (1, 2)
my_dict = {my_tuple: "value"}  # Works
my_list = [1, 2]
# my_dict = {my_list: "value"}  # Raises TypeError

Does removing the first or last item in a list take the same time?

No.
Last item: O(1) (constant time, pop()).
First item: O(n) (linear time, pop(0) shifts elements).

Explanation: Removing the first item requires shifting all elements. Use collections.deque for O(1) at both ends.

my_list = [1, 2, 3]
my_list.pop()  # O(1)
my_list.pop(0)  # O(n)

What is negative indexing in Python?

Negative indexing accesses elements from the end, starting at -1.

Explanation: -1 is the last element, -2 is the second-to-last, etc. Useful for quick access.

my_list = ['a', 'b', 'c']
print(my_list[-1])  # Output: c
print(my_list[-2])  # Output: b

Why do floating-point calculations seem inaccurate?

Floating-point numbers are stored in binary, causing rounding errors for some decimals.

Explanation: Binary representation can’t precisely store numbers like 0.1. Use decimal module for precision.

print(0.1 + 0.2)  # Output: 0.30000000000000004

What are *args and **kwargs?

*args: Variable number of positional arguments (as a tuple).
**kwargs: Variable number of keyword arguments (as a dict).

Explanation: Use *args and **kwargs for flexible function signatures.

def my_func(*args, **kwargs):
    print(args)    # Output: (1, 2, 3)
    print(kwargs)  # Output: {'x': 4, 'y': 5}

my_func(1, 2, 3, x=4, y=5)

How do you iterate through multiple lists simultaneously?

Use the zip() function.

Explanation: zip() pairs elements from multiple iterables into tuples. Use zip(*lists) to unzip.

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
for num, letter in zip(list1, list2):
    print(num, letter)
# Output:
# 1 a
# 2 b
# 3 c

What are the ways to add elements to a list?

append(): Add one item at the end.
extend(): Add multiple items from an iterable.
insert(): Add an item at a specific index.
+ operator: Concatenate lists.

Explanation: Each method suits different needs—append for single items, extend for iterables, etc.

my_list = [1, 2]
my_list.append(3)
print(my_list)  # Output: [1, 2, 3]

my_list.extend([4, 5])
print(my_list)  # Output: [1, 2, 3, 4, 5]

my_list.insert(1, 'x')
print(my_list)  # Output: [1, 'x', 2, 3, 4, 5]

my_list = my_list + [6]
print(my_list)  # Output: [1, 'x', 2, 3, 4, 5, 6]

Write a program to check if a number is prime.

Explanation: The function checks divisibility up to the square root of n, optimizing performance.

from math import sqrt

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

print(is_prime(17))  # Output: True
print(is_prime(4))   # Output: False

What’s the time complexity of the prime check program, and is there a faster way?

Time Complexity: O(√n) for the above program.
Faster Way: Use the Sieve of Eratosthenes for multiple primes (O(n log log n)).
Explanation: The sieve is efficient for generating all primes up to a number.

How do you swap two variables?

Using a temporary variable.
Python’s multiple assignment.

Explanation: Python’s a, b = b, a is concise and efficient.

# Using temp
a, b = 5, 10
temp = a
a = b
b = temp
print(a, b)  # Output: 10 5

# Pythonic way
a, b = 5, 10
a, b = b, a
print(a, b)  # Output: 10 5

Write a recursive program to calculate factorial.

Explanation: Recursion multiplies n by the factorial of n-1 until n=1.

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))  # Output: 120

Is there a faster way to calculate factorial?

Yes, use math.factorial() or iterative methods.

Explanation: math.factorial() is optimized in C, and iterative methods avoid recursion overhead.

from math import factorial
print(factorial(5))  # Output: 120

How do you find the minimum value in a list using a lambda function?

reduce() applies the lambda pairwise to find the minimum. Alternatively, use min().

from functools import reduce

numbers = [5, 2, 8, 1, 9]
min_val = reduce(lambda x, y: x if x < y else y, numbers)
print(min_val)  # Output: 1

Convert a list of characters to a comma-separated string.

Explanation: join() combines elements with a comma delimiter.

chars = ['a', 'b', 'c']
result = ','.join(chars)
print(result)  # Output: a,b,c

How do you find the minimum value in a dictionary?

Explanation: min() with a lambda finds the key with the smallest value.

my_dict = {'a': 5, 'b': 2, 'c': 8}
min_key = min(my_dict, key=lambda k: my_dict[k])
min_value = my_dict[min_key]
print(min_value)  # Output: 2

What are the types of variables in Python OOP?

Class variables: Shared across all instances, defined outside methods.
Instance variables: Unique to each instance, defined in __init__.
Local variables: Defined in methods, scoped to that method.

Explanation: Each variable type has a specific scope and use.

class MyClass:
    class_var = "shared"  # Class variable
    
    def __init__(self, value):
        self.instance_var = value  # Instance variable
    
    def method(self):
        local_var = "local"  # Local variable
        print(self.class_var, self.instance_var, local_var)

obj = MyClass("unique")
obj.method()  # Output: shared unique local

What are the types of methods in Python OOP?

Instance methods: Operate on instance data (use self).
Class methods: Operate on class data (use cls, decorated with @classmethod).
Static methods: Utility functions, no access to self or cls (use @staticmethod).

Explanation: Each method type serves a specific purpose.

class MyClass:
    class_var = "shared"
    
    def instance_method(self):
        return self.class_var
    
    @classmethod
    def class_method(cls):
        return cls.class_var
    
    @staticmethod
    def static_method():
        return "No self or cls"

obj = MyClass()
print(obj.instance_method())  # Output: shared
print(MyClass.class_method()) # Output: shared
print(MyClass.static_method()) # Output: No self or cls

What is inheritance, and how is it useful?

Inheritance allows a child class to inherit attributes/methods from a parent class.

Explanation: Inheritance promotes code reuse and specialization. The child class can override or extend parent behavior.

class Animal:
    def speak(self):
        return "I make a sound"

class Dog(Animal):
    def speak(self):
        return "Woof!"

dog = Dog()
print(dog.speak())  # Output: Woof!

What are access specifiers in Python?

Python uses naming conventions for access control:
Public: No underscore (e.g., var).
Protected: Single underscore (e.g., _var).
Private: Double underscore (e.g., __var).

Explanation: Private variables use name mangling (_ClassName__var). These are conventions, not strict enforcement.

class MyClass:
    def __init__(self):
        self.public = "public"
        self._protected = "protected"
        self.__private = "private"

obj = MyClass()
print(obj.public)      # Output: public
print(obj._protected)  # Output: protected
# print(obj.__private) # Raises AttributeError
print(obj._MyClass__private)  # Output: private (name mangling)

In NumPy, how is array[:, 0] different from array[:, [0]]?

array[:, 0]: Returns the first column as a 1D array.
array[:, [0]]: Returns the first column as a 2D array (column vector).

Explanation: The extra [0] in [0] keeps the column structure.

import numpy as np
arr = np.array([[1, 2], [3, 4]])
print(arr[:, 0])    # Output: [1 3]
print(arr[:, [0]])  # Output: [[1] [3]]

What’s the difference between split() and array_split() in NumPy?

split(): Divides an array into equal parts; raises an error if not possible.
array_split(): Divides into unequal parts if needed.

Explanation: array_split() is more flexible.

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(np.array_split(arr, 3))  # Output: [array([1, 2]), array([3, 4]), array([5])]
# np.split(arr, 3)  # Raises ValueError

How do you convert True/False to 1/0 in a pandas DataFrame?

Explanation: astype(int) converts booleans to integers.

import pandas as pd
df = pd.DataFrame({'flag': [True, False, True]})
df['flag'] = df['flag'].astype(int)
print(df)  # Output:    flag
#            0     1
#            1     0
#            2     1

How are loc() and iloc() different in pandas?

loc(): Access by labels.
iloc(): Access by integer positions.

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3]}, index=['x', 'y', 'z'])
print(df.loc['x', 'A'])  # Output: 1
print(df.iloc[0, 0])     # Output: 1

How do you sort a DataFrame by two columns?

Explanation: sort_values() sorts by the first column, then the second for ties.

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 1], 'B': [3, 1, 2]})
sorted_df = df.sort_values(by=['A', 'B'])
print(sorted_df)
# Output:
#    A  B
# 0  1  2
# 2  1  3
# 1  2  1

How do you find the row with the maximum value in a column?

Explanation: idxmax() returns the index of the maximum value.

import pandas as pd
df = pd.DataFrame({'A': [1, 5, 3]})
max_row = df['A'].idxmax()
print(df.loc[max_row])  # Output: A    5

How do you split a string column into multiple columns?

Explanation: str.split(expand=True) creates a DataFrame from split strings.

import pandas as pd
df = pd.DataFrame({'name': ['Alice Smith', 'Bob Jones']})
split_df = df['name'].str.split(' ', expand=True)
split_df.columns = ['First', 'Last']
print(split_df)
# Output:
#   First   Last
# 0 Alice  Smith
# 1   Bob  Jones

What’s the difference between map() and applymap() in pandas?

map(): Applies a function to a Series.
applymap(): Applies a function to every element in a DataFrame.

Explanation: map() is for Series; applymap() is for DataFrames.

import pandas as pd
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
print(df['A'].map(lambda x: x * 2))  # Output: 0    2
                                     #         1    4
print(df.applymap(lambda x: x * 2))
# Output:
#    A  B
# 0  2  6
# 1  4  8

How do you invert True/False values in a pandas query?

Use the ~ operator.

Explanation: ~ flips boolean values.

import pandas as pd
df = pd.DataFrame({'A': [True, False, True]})
df['A'] = ~df['A']
print(df)  # Output:       A
#            0  False
#            1   True
#            2  False

How do you calculate percentage change between rows in pandas?

Explanation: pct_change() computes the fractional change from the previous row.

import pandas as pd
df = pd.DataFrame({'A': [100, 110, 121]})
df['pct_change'] = df['A'].pct_change()
print(df)
# Output:
#      A  pct_change
# 0  100         NaN
# 1  110         0.1
# 2  121         0.1

How do you calculate the coefficient of variation in pandas?

Explanation: Coefficient of variation is standard deviation divided by mean.

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3, 4, 5]})
cv = df['A'].std() / df['A'].mean()
print(cv)  # Output: 0.4472135954999579

How do you remove leading whitespace from a string?

Use lstrip().

Explanation: lstrip() removes leading spaces (use rstrip() for trailing, strip() for both).

text = "   FunWithAI"
print(text.lstrip())  # Output: FunWithAI

What is enumerate() in Python?

enumerate() iterates over a sequence, returning index-value pairs.

Explanation: enumerate() simplifies loops needing indices.

fruits = ['apple', 'banana', 'cherry']
for index, value in enumerate(fruits):
    print(index, value)
# Output:
# 0 apple
# 1 banana
# 2 cherry

What are deepcopy and shallowcopy?

Shallow copy: Copies references to nested objects (changes affect both).
Deep copy: Copies all nested objects (independent copies).

Explanation: Deep copies are safer for nested structures.

from copy import copy, deepcopy
lst = [[1, 2], 3]
shallow = copy(lst)
deep = deepcopy(lst)

shallow[0][0] = 99
print(lst)      # Output: [[99, 2], 3]
print(deep)     # Output: [[1, 2], 3]

What is a callable object in Python?

A callable object can be invoked with () (e.g., functions, classes).

Explanation: Use callable() to check. Non-callables lack ().

def my_func():
    print("Hello")
print(callable(my_func))  # Output: True
my_func()  # Output: Hello

How do you find unique elements and their counts in a list using NumPy?

Explanation: np.unique(return_counts=True) returns arrays of unique values and their counts.

import numpy as np
lst = [1, 2, 2, 3, 3, 3]
values, counts = np.unique(lst, return_counts=True)
print(dict(zip(values, counts)))  # Output: {1: 1, 2: 2, 3: 3}

What’s the difference between indexing and slicing in NumPy?

Indexing: Accesses a single element (e.g., arr[0]).
Siscing: Accesses a range of elements (e.g., arr[0:2]).

Explanation: Slicing creates a view (shallow copy), while indexing returns a scalar or array.

import numpy as np
arr = np.array([1, 2, 3])
print(arr[0])      # Output: 1 (indexing)
print(arr[0:2])    # Output: [1 2] (slicing)

How do you get indices of the N largest values in a NumPy array?

Explanation: argsort() gives indices of sorted values; slice the last n and reverse.

import numpy as np
arr = np.array([5, 2, 8, 1, 9])
n = 2
indices = np.argsort(arr)[-n:][::-1]
print(indices)  # Output: [4 2]

Conclusion

Wow, you made it through 75+ Python interview questions! I hope this guide has boosted your confidence and given you a solid foundation to tackle any Python interview. At FunWithAI.in, we’re all about making learning fun and practical, and these questions double as tutorials for freshers and pros alike. Keep practicing, explore more Python tips on our blog, and you’ll be ready to impress at your next interview.

Leave a Comment