0% found this document useful (0 votes)
39 views75 pages

Nezir Zahirovic - The Python Interview Handbook 2023 - 112+ Q&A (2023)

The Python Interview Handbook provides essential questions and answers for preparing for Python-related job interviews, covering various topics such as data structures, algorithms, and Python functionalities. It includes practical coding examples and explanations to help candidates understand key concepts and improve their interview performance. The book also emphasizes the importance of perseverance and offers encouragement to those facing interview challenges.

Uploaded by

Prahalad Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views75 pages

Nezir Zahirovic - The Python Interview Handbook 2023 - 112+ Q&A (2023)

The Python Interview Handbook provides essential questions and answers for preparing for Python-related job interviews, covering various topics such as data structures, algorithms, and Python functionalities. It includes practical coding examples and explanations to help candidates understand key concepts and improve their interview performance. The book also emphasizes the importance of perseverance and offers encouragement to those facing interview challenges.

Uploaded by

Prahalad Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

The Python

Interview
HANDBOOK
Your best guide with Essential
Questions and Answers!

Copyright © 2023 Nezir Zahirovic


All rights reserved InterviewBible.com
VISIT INTERVIEWBIBLE.COM FOR MORE E-BOOKS!

Here are new titles on our store:

The Python Interview Handbook 2023, e-book with 500+ questions


and answers!
The Ruby On Rails Interview Bible 2023, e-book with 500+ questions
and answers!
The JavaScript Interview Bible 2023, e-book with 1000+ interview
questions and answers!
The React JS Interview Handbook, e-book with 120+ questions and
answers for FREE!

Buy on

1
DEDICATION
To all those who struggle at interviews,

This book is dedicated to you. We understand how stressful and


overwhelming the interview process can be, and we want you to know
that you are not alone.

We know that sometimes it feels like you'll never be able to impress an


interviewer or land your dream job. But we believe in you, and we want
to equip you with the knowledge and tools you need to succeed.

Throughout these pages, you'll find valuable tips and advice to help you
navigate the interview process with confidence. We hope that by reading
this book, you'll gain the skills and insights you need to ace your next
interview and secure the job you've been dreaming of.

Remember, interviews can be challenging, but they are also


opportunities for growth and learning. With perseverance and the right
mindset, you can overcome any obstacle and achieve your goals.

So, here's to you, the brave souls who keep pushing forward in the face
of adversity. We salute you and wish you all the best in your interview
journey.

Sincerely,

One of you!

All rights reserved InterviewBible.com 2023


DISCLAIMER
The information provided in this book is for educational and interview
preparation purposes. The author has made effort to ensure the accuracy
of the information within this book was correct at time of publication.
However, the author makes no representation or warranties with respect
to the accuracy or completeness of the contents of this book and
specifically disclaims any implied warranties of merchantability or fitness
for any particular purpose.

The information in this book is sold without any warranty, express or


implied. The author will not be held liable for any damages, direct or
indirect, arising from the use of information contained in this book.

The views and opinions expressed in this book are those of the author
and do not necessarily reflect the official and latest policy or position of
any company, organization, or institution. Any mention of commercial
products, processes, or services within this book does not constitute an
endorsement or recommendation by the author.

The author has taken all reasonable care to ensure that any examples,
code snippets, or technical information provided in this book are accurate
and up to date. However, the author cannot guarantee that the code will
work in all situations and it is the responsibility of the reader to test and
modify the code to meet their specific requirements. The author will not
be held liable for any damages, direct or indirect, arising from the use or
misuse of the code contained in this book.

Finally, the author would like to express their gratitude to all the
contributors, reviewers, and readers of this book. Your feedback,
suggestions, and support have been invaluable in creating this
comprehensive guide to Python interview preparation.

All rights reserved InterviewBible.com 2023


AKNOWLEDGMENTS
I would like to express my deepest gratitude to everyone who
contributed to the creation of this book, "The Python Interview
Handbook".

First and foremost, I would like to thank the Python community for
creating and sharing their knowledge and experience, which was
instrumental in the making of this book. Without their contributions and
support, this book would not have been possible.

I would also like to thank my family and friends for their unwavering
support and encouragement throughout this project. Your love and
encouragement kept me motivated and focused during the long hours of
research and writing.

I would also like to thank the team at OpenAI for providing the
technology that powers ChatGPT, the AI language model that assisted in
generating content for this book.

Finally, I would like to thank the readers of this book for their interest in
Python and for considering this handbook as a resource to enhance their
knowledge and skills. I hope this book provides value and helps you in
your journey to becoming a proficient Python developer.

All rights reserved InterviewBible.com 2023


CONTENTS

Python Machine Learning


Testing Microservices
Debugging App Architecture
Database Payment Processing
Deployment Tools & Resources
Security Python Frameworks
Memory Management Django
Error Handling Flask
Concurrency NumPy
Routing Matplotlib
Performance and Scalability Programming Jokes

All rights reserved InterviewBible.com 2023


Python
Python is a high-level, interpreted programming language that is used for
a wide range of applications, including web development, data analysis,
artificial intelligence, and scientific computing.

1) Write a Python function to check whether a given


number is prime or not.

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

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

2 All rights reserved InterviewBible.com 2023


2) Write a Python function to find the largest
continuous sum in a given list of integers.

def largest_continuous_sum(numbers):
max_sum = current_sum = numbers[0]
for n in numbers[1:]:
current_sum = max(current_sum + n, n)
max_sum = max(max_sum, current_sum)
return max_sum

# Example usage:
print(largest_continuous_sum([1, -2, 3, 4, -1, 2, -6, 5]))
# Output: 10

3) What is the difference between 'is' and '==' in


Python?

The 'is' operator in Python checks if two objects are the same
object (i.e., they have the same memory address), whereas the
'==' operator checks if two objects have the same value. Here's an
example:

3 All rights reserved InterviewBible.com 2023


# create two different lists with the same elements
list1 = [1, 2, 3]
list2 = [1, 2, 3]

# use 'is' to check if they are the same object


print(list1 is list2) # Output: False

# use '==' to check if they have the same value


print(list1 == list2) # Output: True

4) What is the purpose of the 'enumerate' function in


Python? Provide an example.

The 'enumerate' function in Python is used to iterate over an


iterable (such as a list) and return a tuple for each element that
includes the index of the element and the element itself. Here's an
example:

my_list = ['a', 'b', 'c']


for i, value in enumerate(my_list):
print(f"Index: {i}, Value: {value}")

4 All rights reserved InterviewBible.com 2023


5) What is the purpose of the 'zip' function in Python?
Provide an example.

The 'zip' function in Python is used to combine multiple iterables


(such as lists) into a single iterable that produces tuples of
corresponding elements from each of the input iterables. Here's an
example:

# create two lists


list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

# use the 'zip' function to combine the lists


combined_list = list(zip(list1, list2))

# print the resulting list of tuples


print(combined_list) # Output: [(1, 'a'), (2, 'b'), (3, 'c')]

5 All rights reserved InterviewBible.com 2023


6) What is the purpose of the 'yield' keyword in
Python? Provide an example.

The 'yield' keyword is used in a function to define a generator that


can be iterated over using a 'for' loop. When the 'yield' keyword is
encountered in the function, the current state of the function is
saved and the yielded value is returned to the caller. The next time
the function is called, execution resumes from where it left off, with
the saved state restored. Here's an example:

# define a generator function that yields a sequence of squares


def squares(n):
for i in range(n):
yield i**2

# use the generator to print the first 5 squares


for square in squares(5):
print(square) # Output: 0, 1, 4, 9, 16

6 All rights reserved InterviewBible.com 2023


7) What is the difference between a list
comprehension and a generator expression in Python?
Provide an example of each.

A list comprehension is a concise way to create a new list by


applying an expression to each element of an existing list or
iterable. A generator expression is similar, but instead of creating a
new list, it creates a generator object that can be iterated over. The
key difference is that a list comprehension creates the entire list in
memory all at once, whereas a generator expression generates
values on-the-fly as they are needed. Here are examples of each:

# create a new list using a list comprehension


numbers = [1, 2, 3, 4, 5]
squared_numbers = [x**2 for x in numbers]
print(squared_numbers) # Output: [1, 4, 9, 16, 25]

# create a generator expression


numbers = [1, 2, 3, 4, 5]
squared_numbers = (x**2 for x in numbers)

# iterate over the generator to print the squared numbers


for square in squared_numbers:
print(square) # Output: 1, 4, 9, 16, 25

7 All rights reserved InterviewBible.com 2023


8) Write a Python function to check whether a given
string is a palindrome or not.

def is_palindrome(s):
return s == s[::-1]

# Example usage:
print(is_palindrome('racecar')) # Output: True
print(is_palindrome('hello')) # Output: False

9) Write a Python function to find the second highest


number in a list.

def second_highest(numbers):
numbers = sorted(set(numbers))
return numbers[-2] if len(numbers) >= 2 else None

# Example usage:
print(second_highest([1, 3, 2, 4, 4, 5])) # Output: 4
print(second_highest([1])) # Output: None

8 All rights reserved InterviewBible.com 2023


10) Write a Python function to count the number of
vowels in a given string.

def count_vowels(s):
return sum(1 for c in s.lower() if c in 'aeiou')

# Example usage:
print(count_vowels('hello world')) # Output: 3

11) Write a Python function to find the common


elements between two lists.

def common_elements(list1, list2):


return list(set(list1) & set(list2))

# Example usage:
print(common_elements([1, 2, 3], [2, 3, 4])) # Output: [2, 3]

9 All rights reserved InterviewBible.com 2023


12) Write a Python function to reverse a linked list.

class Node:
def __init__(self, data):
self.data = data
self.next = None

def reverse_list(head):
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev

# Example usage:
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
reversed_head = reverse_list(head)
print(reversed_head.data) # Output: 3
print(reversed_head.next.data) # Output: 2
print(reversed_head.next.next.data) # Output: 1

10 All rights reserved InterviewBible.com 2023


13) Write a Python function to find the shortest path
between two nodes in a graph.

from collections import deque

def shortest_path(graph, start, end):


queue = deque([(start, [start])])
visited = set()
while queue:
node, path = queue.popleft()
if node == end:
return path
if node in visited:
continue
visited.add(node)
for neighbor in graph[node]:
queue.append((neighbor, path + [neighbor]))
return None

# Example usage:
graph = {'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'],
'D': [], 'E': [], 'F': []}
print(shortest_path(graph, 'A', 'F'))
# Output: ['A', 'C', 'F']

11 All rights reserved InterviewBible.com 2023


14) Write a Python function to find the intersection of
two sorted lists.

def intersection(list1, list2):


i, j = 0, 0
result = []
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
i += 1
elif list1[i] > list2[j]:
j += 1
else:
result.append(list1[i])
i += 1
j += 1
return result

# Example usage:
print(intersection([1, 2, 3, 4, 5], [2, 4, 6]))
# Output: [2, 4]

12 All rights reserved InterviewBible.com 2023


15) Write a Python function to find the longest
common prefix among a list of strings.

def longest_common_prefix(strings):
if not strings:
return ''
for i, c in enumerate(strings[0]):
for s in strings[1:]:
if i >= len(s) or s[i] != c:
return strings[0][:i]
return strings[0]

# Example usage:
print(longest_common_prefix(['flower', 'flow', 'flight']))
# Output: 'fl'

13 All rights reserved InterviewBible.com 2023


16) Write a Python function to perform a binary
search on a sorted list.

def binary_search(numbers, target):


left, right = 0, len(numbers) - 1
while left <= right:
mid = (left + right) // 2
if numbers[mid] == target:
return mid
elif numbers[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1

# Example usage:
print(binary_search([1, 3, 5, 7, 9], 5)) # Output: 2
print(binary_search([1, 3, 5, 7, 9], 2)) # Output: -1

14 All rights reserved InterviewBible.com 2023


17) Write a Python function to find the maximum sum
of a contiguous subarray with a size of k in a given list
of integers.

def max_sum_subarray(numbers, k):


max_sum = current_sum = sum(numbers[:k])
for i in range(k, len(numbers)):
current_sum = current_sum - numbers[i - k] + numbers[i]
max_sum = max(max_sum, current_sum)
return max_sum

# Example usage:
print(max_sum_subarray([1, 2, 3, 4, 5], 2)) # Output: 9
print(max_sum_subarray([100, 200, 300, 400], 2)) # Output: 700

15 All rights reserved InterviewBible.com 2023


18) Write a Python function to implement a stack
using a linked list.

class Node:
def __init__(self, data):
self.data = data
self.next = None

class Stack:
def __init__(self):
self.head = None

def push(self, data):


new_node = Node(data)
new_node.next = self.head
self.head = new_node

def pop(self):
if self.head is None:
return None
popped_node = self.head
self.head = self.head.next
popped_node.next = None
return popped_node.data

def is_empty(self):
return self.head is None

# Example usage:
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop()) # Output: 3
print(stack.pop()) # Output: 2
print(stack.is_empty()) # Output: False

16 All rights reserved InterviewBible.com 2023


19) Write a Python function to implement a queue
using two stacks.

class Queue:
def __init__(self):
self.stack1 = []
self.stack2 = []

def enqueue(self, data):


self.stack1.append(data)

def dequeue(self):
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
if not self.stack2:
return None
return self.stack2.pop()

def is_empty(self):
return not self.stack1 and not self.stack2

# Example usage:
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue.dequeue()) # Output: 1
print(queue.dequeue()) # Output: 2
print(queue.is_empty()) # Output: False

17 All rights reserved InterviewBible.com 2023


20) Write a Python function to find the longest
increasing subsequence in a given list of integers.

def longest_increasing_subsequence(numbers):
n = len(numbers)
dp = [1] * n
for i in range(1, n):
for j in range(i):
if numbers[i] > numbers[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)

# Example usage:
print(longest_increasing_subsequence(
[10, 9, 2, 5, 3, 7, 101, 18]))
# Output: 4

18 All rights reserved InterviewBible.com 2023


21) Write a Python function to find the shortest path
between two nodes in a graph using Dijkstra's
algorithm.

import heapq

def dijkstra(graph, start, end):


heap = [(0, start, [])]
visited = set()
while heap:
(cost, node, path) = heapq.heappop(heap)
if node not in visited:
visited.add(node)
path = path + [node]
if node == end:
return path
for neighbor, c in graph[node].items():
heapq.heappush(heap, (cost + c, neighbor, path))
return None

# Example usage:
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 2, 'D': 5},
'C': {'A': 4, 'B': 2, 'D': 1},
'D': {'B': 5, 'C': 1}
}
print(dijkstra(graph, 'A', 'D')) # Output: ['A', 'C', 'D']

19 All rights reserved InterviewBible.com 2023


22) Write a Python function to find the longest
common substring between two given strings.

def longest_common_substring(str1, str2):


m = len(str1)
n = len(str2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
longest_substring = ""
for i in range(1, m + 1):
for j in range(1, n + 1):
if str1[i - 1] == str2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
if dp[i][j] > len(longest_substring):
longest_substring = str1[i - dp[i][j]:i]
else:
dp[i][j] = 0
return longest_substring

# Example usage:
print(longest_common_substring("abcdefg", "defghi"))
# Output: "def"

20 All rights reserved InterviewBible.com 2023


VISIT INTERVIEWBIBLE.COM FOR MORE E-BOOKS!

Here are new titles on our store:

The Python Interview Handbook 2023, e-book with 500+ questions


and answers!
The Ruby On Rails Interview Bible 2023, e-book with 500+ questions
and answers!
The JavaScript Interview Bible 2023, e-book with 1000+ interview
questions and answers!
The React JS Interview Handbook, e-book with 120+ questions and
answers for FREE!

Buy on

21
23) Write a Python function to check if a given string
is a palindrome.

def is_palindrome(s):
i = 0
j = len(s) - 1
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
# Example usage:
print(is_palindrome("racecar")) # Output: True
print(is_palindrome("hello")) # Output: False

24) Write a Python function to sort a given list of


integers using the quicksort algorithm.

def quicksort(numbers):
if len(numbers) <= 1:
return numbers
pivot = numbers[0]
less = []
greater = []
for number in numbers[1:]:
if number <= pivot:
less.append(number)
else:
greater.append(number)
return quicksort(less) + [pivot] + quicksort(greater)
# Example usage:
print(quicksort([3, 2, 1, 5, 4])) # Output: [1, 2, 3, 4, 5]

22 All rights reserved InterviewBible.com 2023


25) Write a Python function to generate all
permutations of a given list of integers.

import itertools

def permutations(numbers):
return list(itertools.permutations(numbers))

# Example usage:
print(permutations([1, 2, 3]))
# Output: [(1, 2, 3), (1, 3, 2), (2, 1, 3),
# (2, 3, 1), (3, 1, 2), (3, 2, 1)]

26) Write a Python function to merge two sorted


arrays into a single sorted array.

def merge_sorted_arrays(arr1, arr2):


merged = []
i = 0
j = 0
while i < len(arr1) and j < len(arr2):
if arr1[i] <= arr2[j]:
merged.append(arr1[i])
i += 1
else:
merged.append(arr2[j])
j += 1
merged += arr1[i:]
merged += arr2[j:]
return merged

# Example usage:
print(merge_sorted_arrays([1, 3, 5], [2, 4, 6]))
# Output: [1, 2, 3, 4, 5, 6]

23 All rights reserved InterviewBible.com 2023


27) Write a Python function to find the maximum
subarray sum in a given array of integers.

def max_subarray_sum(arr):
max_sum = 0
current_sum = 0
for num in arr:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum

# Example usage:
print(max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
# Output: 6

28) Write a Python function to find the first non-


repeating character in a given string.

def first_non_repeating_char(s):
count = {}
for char in s:
count[char] = count.get(char, 0) + 1
for char in s:
if count[char] == 1:
return char
return None

# Example usage:
print(first_non_repeating_char("hello")) # Output: "h"

24 All rights reserved InterviewBible.com 2023


29) Write a Python function to reverse a given linked
list.

class Node:
def __init__(self, data=None):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None

def insert(self, data):


node = Node(data)
if self.head is None:
self.head = node
else:
current = self.head
while current.next is not None:
current = current.next
current.next = node

def reverse(self):
previous = None
current = self.head
while current is not None:
next_node = current.next
current.next = previous
previous = current
current = next_node
self.head = previous

def print_list(self):
current = self.head
while current is not None:
print(current.data, end=" ")
current = current.next
print()

25 All rights reserved InterviewBible.com 2023


# Example usage:
linked_list = LinkedList()
linked_list.insert(1)
linked_list.insert(2)
linked_list.insert(3)
linked_list.print_list() # Output: 1 2 3
linked_list.reverse()
linked_list.print_list() # Output: 3 2 1

30) Write a Python function to implement binary


search on a given sorted array of integers.

def binary_search(arr, target):


low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1

# Example usage:
print(binary_search([1, 2, 3, 4, 5], 3)) # Output: 2
print(binary_search([1, 2, 3, 4, 5], 6)) # Output: -1

26 All rights reserved InterviewBible.com 2023


31) Write a Python function to implement the merge
sort algorithm to sort a given list of integers.

def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)

def merge(left, right):


result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result

# Example usage:
arr = [3, 1, 4, 2, 5]
print(merge_sort(arr)) # Output: [1, 2, 3, 4, 5]

27 All rights reserved InterviewBible.com 2023


32) Write a Python function to implement the
quicksort algorithm to sort a given list of integers.

def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)

# Example usage:
arr = [3, 1, 4, 2, 5]
print(quicksort(arr)) # Output: [1, 2, 3, 4, 5]

28 All rights reserved InterviewBible.com 2023


33) Write a Python function to implement the
breadth-first search algorithm to traverse a given
tree.

class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data

def bfs(root):
if root is None:
return
queue = [root]
while len(queue) > 0:
node = queue.pop(0)
print(node.data, end=" ")
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)

# Example usage:
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
bfs(root) # Output: 1 2 3 4 5

29 All rights reserved InterviewBible.com 2023


34) Write a Python function to implement the depth-
first search algorithm to traverse a given tree.

class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data

def dfs(root):
if root is None:
return
print(root.data, end=" ")
dfs(root.left)
dfs(root.right)
# Example usage:
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
dfs(root) # Output: 1 2 4 5 3

35) What is the output of the following code?

The output is [1, 2, 3, 4]. This is because b is just a reference to the


same list as a, so modifying a also modifies b.

a = [1, 2, 3]
b = a
a.append(4)
print(b)
30 All rights reserved InterviewBible.com 2023
36) What is the output of the following code?

The output is "hello". Unlike lists, strings are immutable in Python,


so the += operator creates a new string instead of modifying the
original one. b still refers to the original string "hello".

a = "hello"
b = a
a += " world"
print(b)

37) What is the output of the following code?

The output is [1, 2, 3]. The [:] slice notation creates a new copy of
the list, so b refers to a different list than a. Modifying a does not
affect b.

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

31 All rights reserved InterviewBible.com 2023


38) What is the output of the following code?

The output is 10 5. This is a common trick in Python for swapping


two variables without needing a temporary variable. The right-hand
side creates a tuple (b, a), which is then unpacked into a and b.

a = 5
b = 10
a, b = b, a
print(a, b)

39) What is the output of the following code?

The output is [1, 2, 3]. The copy() method creates a new copy of
the list, so b refers to a different list than a. Modifying a does not
affect b.

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

32 All rights reserved InterviewBible.com 2023


40) What is the output of the following code?

The output is [1, 2, 3]. Reassigning a to a new list creates a new


object, so b still refers to the original list [1, 2, 3].

a = [1, 2, 3]
b = a
a = [4, 5, 6]
print(b)

41) What is the output of the following code?

This code will raise a TypeError because strings are immutable in


Python and cannot be modified in place.

a = "hello"
a[0] = "H"
print(a)

33 All rights reserved InterviewBible.com 2023


42) What is the output of the following code?

The output is still [1, 2, 3]. The + operator creates a new list, but
does not modify the original lists a and b.

a = [1, 2, 3]
b = [4, 5, 6]
a + b
print(a)

43) What is the output of the following code?

The output is [1, 2, 3, 4]. b and c are just references to the same
list as a,

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

34 All rights reserved InterviewBible.com 2023


44) What is the output of the following code?

The output is ["apple", "banana", "orange"]. When you call sorted()


on a dictionary, it only returns a list of the keys in the dictionary,
not the values.

a = {"apple": 3, "banana": 2, "orange": 1}


b = sorted(a)
print(b)

45) What is the output of the following code?

The output is True and False. The == operator checks if the values
of a and b are equal, which they are, but the is operator checks if
they are the same object, which they are not.

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
print(a is b)

35 All rights reserved InterviewBible.com 2023


46) What is the output of the following code?

The output is "hello". Strings are immutable in Python, so calling


upper() on a creates a new string, but b still refers to the original
string "hello".

a = "hello"
b = a
a = a.upper()
print(b)

47) What is the output of the following code?

The output is [1, 2, 3, 1, 2, 3]. The *= operator modifies the list in


place by repeating its elements.

a = [1, 2, 3]
a *= 2
print(a)

36 All rights reserved InterviewBible.com 2023


48) What is the output of the following code?

The output is True and False. The == operator checks if the values
of a and b are equal, which they are, but the is operator checks if
they are the same object, which they are not.

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
print(a is b)

49) What is the output of the following code?

This code will raise a KeyError because "pear" is not a key in the
dictionary a.

a = {"apple": 3, "banana": 2, "orange": 1}


print(a["pear"])

37 All rights reserved InterviewBible.com 2023


50) What is the output of the following code?

The output is False. As we saw in an earlier question, the +=


operator creates a new string instead of modifying the original one.
a and b refer to different string objects.

a = "hello"
b = a
a += " world"
print(a is b)

51) What is the output of the following code?

The output is [1, 2, 3] and [1, 2, 3, 4]. b is a copy of a, so it is not


affected by the append operation, but c is just a reference to the
same list as a, so it is modified.

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

a.append(4)

print(b)
print(c)

38 All rights reserved InterviewBible.com 2023


52) What is the output of the following code?

The output is ["orange", "banana", "apple"]. The sorted() function


sorts the dictionary keys.

a = {"apple": 3, "banana": 2, "orange": 1}


print(sorted(a, key=lambda x: a[x]))

53) What is an API in Python?

: API stands for Application Programming Interface, which is a set of


protocols and tools for building software applications. In Python, an
API is a set of rules, protocols, and tools for building software
applications that interact with other software or hardware systems.

54) What are the types of APIs in Python?

There are two types of APIs in Python: the built-in Python API, which
provides access to Python's built-in functions and modules, and
third-party APIs, which are created by other developers and provide
access to external services and systems.

39 All rights reserved InterviewBible.com 2023


55) What is the built-in Python API?

The built-in Python API is a set of functions, modules, and classes


that are built into the Python language itself. It provides access to a
wide range of functionality, from basic data types and control
structures to advanced features like networking and concurrency

56) What are some examples of modules in the built-


in Python API?

Some examples of modules in the built-in Python API include os for


operating system interactions, sys for system-specific parameters
and functions, datetime for working with dates and times, and
math for mathematical functions.

57) What are some examples of functions in the built-


in Python API?

Some examples of functions in the built-in Python API include


print() for printing output to the console, len() for getting the length
of a sequence, range() for generating a sequence of numbers, and
type() for getting the type of an object.

40 All rights reserved InterviewBible.com 2023


58) What is a third-party API in Python?

A third-party API in Python is an API that is created by a third-party


developer or organization, rather than being built into the Python
language itself. These APIs provide access to external services and
systems, such as social media platforms, payment gateways, and
weather data.

59) What are some popular third-party APIs in


Python?

Some popular third-party APIs in Python include the Twitter API, the
Google Maps API, the Stripe API for payment processing, and the
OpenWeatherMap API for weather data.

60) What is the process for using a third-party API in


Python?

To use a third-party API in Python, you typically need to obtain an


API key or access token from the provider, which you then use to
authenticate your requests. You then make HTTP requests to the
API endpoint, typically using a library like requests, and parse the
response data to extract the information you need.

41 All rights reserved InterviewBible.com 2023


61) What is an API wrapper in Python?

An API wrapper in Python is a library or module that provides a


higher-level, more convenient interface for working with a
particular API. It often encapsulates the low-level details of making
HTTP requests and parsing responses, making it easier to integrate
the API into your application.

62) What is an API client in Python?

An API client in Python is a program or module that uses an API to


interact with an external service or system. It typically includes
functionality for making requests to the API, handling errors and
exceptions, and parsing response data.

63) What is an API endpoint in Python?

An API endpoint in Python is a specific URL that represents a


particular resource or functionality within an API. It is typically
accessed using HTTP requests, such as GET, POST, PUT, and
DELETE, and returns a response in a specified format, such as JSON
or XML.

42 All rights reserved InterviewBible.com 2023


64) What is SOAP API in Python?

SOAP (Simple Object Access Protocol) API is another type of API


architecture that uses XML-based messages to perform CRUD
operations on resources. It is less popular than REST API and often
used for more complex applications.

65) What is the difference between REST API and


SOAP API in Python?

REST API is more lightweight and simpler than SOAP API, and uses
HTTP requests and JSON or XML data formats. SOAP API, on the
other hand, uses XML messages and more complex protocols, and
is often used for more enterprise-level applications.

66) How do you authenticate with a REST API in


Python?

Authentication with a REST API in Python typically involves


obtaining an access token or API key from the provider, which is
then included in each request to the API. There are also various
authentication methods, such as OAuth 2.0, which can be used to
securely authenticate users.

43 All rights reserved InterviewBible.com 2023


67) How do you handle errors and exceptions when
working with APIs in Python?

When working with APIs in Python, it's important to handle errors


and exceptions in a way that gracefully handles unexpected
responses or errors from the API. This can involve checking the
response status codes, parsing error messages, and retrying failed
requests.

68) How do you rate limit requests to an API in


Python?

To prevent overloading an API with requests, it's important to


implement rate limiting in your Python code. This can involve
setting a maximum number of requests per second or per minute,
or using a third-party library or service to manage rate limiting for
you.

69) How do you cache API responses in Python?

Caching API responses in Python can help improve performance


and reduce the number of requests made to the API. This can
involve using a caching library like requests-cache or cachetools, or
implementing your own custom caching logic using Python's built-in
data structures.

44 All rights reserved InterviewBible.com 2023


70) How do you test API integrations in Python?

Testing API integrations in Python can involve writing automated


tests using a testing framework like unittest or pytest, and using
mock API responses to simulate different scenarios. It can also
involve manual testing using tools like curl or Postman to manually
test API requests and responses.

71) How do you document your API integrations in


Python?

Documenting your API integrations in Python can involve writing


clear, concise documentation that outlines the API endpoints,
parameters, response formats, and any authentication or rate
limiting requirements. This can be done using tools like Swagger or
API Blueprint, or by creating custom documentation using a tool like
Sphinx.

72) What is metaprogramming in Python, and how is


it useful?

Metaprogramming in Python is the ability to modify or generate


Python code at runtime. This can be useful for creating flexible and
reusable code, generating code based on user input, or for
modifying the behavior of existing code. Metaprogramming in
Python can be achieved using techniques like decorators,
metaclasses, and dynamic code generation.
45 All rights reserved InterviewBible.com 2023
73) List some of the most commonly used Python
libraries.

NumPy - a library for numerical computing with Python,


providing tools for working with large multi-dimensional arrays
and matrices.
Pandas - a library for data manipulation and analysis, providing
tools for reading and writing data to and from various file
formats, cleaning and transforming data, and performing basic
statistical analysis.
Matplotlib - a library for creating static, animated, and
interactive visualizations in Python, providing a variety of
plotting functions and customization options.
SciPy - a library for scientific computing with Python, providing
tools for optimization, integration, interpolation, signal and
image processing, and more.
Scikit-learn - a library for machine learning in Python, providing
tools for classification, regression, clustering, and
dimensionality reduction.
TensorFlow - a library for machine learning and deep learning
in Python, providing tools for building and training neural
networks.
Keras - a high-level API for building and training neural
networks in Python, built on top of TensorFlow.
PyTorch - a library for machine learning and deep learning in
Python, providing tools for building and training neural
networks, and emphasizing ease-of-use and flexibility.
Requests - a library for making HTTP requests in Python,
providing a simple and elegant API for sending and receiving
data over the web.

46
Django - a high-level web framework for building web
applications in Python, providing tools for handling routing,
templating, authentication, and more.
Flask - a lightweight web framework for building web
applications in Python, providing a simple and flexible API for
handling requests and responses.
Pillow - a library for working with images in Python, providing
tools for opening, manipulating, and saving images in various
file formats.
Pygame - a library for building games and other multimedia
applications in Python, providing tools for handling input,
graphics, sound, and more.
OpenCV - a library for computer vision and machine learning in
Python, providing tools for image and video processing, object
detection and tracking, and more.
NLTK - a library for natural language processing with Python,
providing tools for tokenization, stemming, tagging, parsing,
and more.
Flask-RESTful - a library for building RESTful APIs in Python
using the Flask framework, providing tools for defining
endpoints, handling requests and responses, and more.
Celery - a library for distributed task scheduling and
management in Python, providing tools for running tasks
asynchronously and in parallel across multiple nodes.
Gunicorn - a library for running Python web applications behind
a reverse proxy server, providing tools for handling multiple
worker processes and managing server resources.
SQLAlchemy - a library for working with databases in Python,
providing tools for defining and querying database tables,
managing transactions, and more.

47
74) What are some common design patterns used in
Python, and can you explain how they are used?

A: Some common design patterns used in Python include the


Singleton pattern, the Factory pattern, and the Observer pattern.
The Singleton pattern ensures that only one instance of a class can
exist at a time, the Factory pattern provides a way to create objects
without specifying the exact class of object that will be created, and
the Observer pattern defines a one-to-many relationship between
objects so that when one object changes state, all its dependents
are notified and updated. These patterns are useful for creating
modular and maintainable code in Python.

75) Can you explain the difference between an


abstract class and an interface in Python?

In Python, an abstract class is a class that cannot be instantiated


directly and is only meant to be subclassed. It can define some
methods and properties that must be implemented by its
subclasses. An interface, on the other hand, is a set of methods and
properties that a class must implement to satisfy a contract. Python
does not have a built-in concept of interfaces, but they can be
emulated using abstract classes and methods.

48 All rights reserved InterviewBible.com 2023


76) Can you explain how Python's garbage collection
works, and what are some strategies for managing
memory usage?

Python's garbage collection system automatically frees up memory


used by objects that are no longer referenced by any part of the
program. The garbage collector runs periodically and removes any
objects that are no longer in use. To manage memory usage in
Python, you can use tools like the sys module to monitor memory
usage, or use techniques like caching, memoization, or lazy loading
to reduce the amount of memory used at any one time.

77) Explain the Global Interpreter Lock (GIL) in Python


and its implications for concurrency.

The Global Interpreter Lock (GIL) in Python is a mechanism that


ensures that only one thread at a time executes Python bytecodes.
This means that Python can't truly utilize multiple CPU cores for a
single process, since only one thread can execute at a time. As a
result, concurrency in Python is often achieved using subprocesses,
multiple processes, or asynchronous programming.

49 All rights reserved InterviewBible.com 2023


78) What is the difference between deep and shallow
copying in Python, and when would you use each?

In Python, a shallow copy creates a new object with the same


reference as the original object, while a deep copy creates a new
object with a new reference. Shallow copies are used to create a
new object that shares some of the original object's attributes,
while deep copies are used to create a completely new and
independent object.

79) How do you count the number of occurrences of


an element in a list in Python?

# Answer
lst = [1, 2, 3, 3, 4, 4, 4, 5]
count_4 = lst.count(4)
print(count_4)
# Output: 3

80) How do you remove all whitespace from a string


in Python?

# Answer
s = " hello world "
no_whitespace_s = s.replace(" ", "")
print(no_whitespace_s)
# Output: "helloworld"

50 All rights reserved InterviewBible.com 2023


81) How do you get the current working directory in
Python?

# Answer
import os
cwd = os.getcwd()
print(cwd)

82) How do you flatten a nested list in Python?

# Answer
nested_lst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flattened_lst = [item for sublist in nested_lst for item
in sublist]
print(flattened_lst)
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

51 All rights reserved InterviewBible.com 2023


83) How do you check if a number is prime in Python?

# Answer
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

print(is_prime(7)) # True
print(is_prime(12)) # False

84) How do you convert a string to a datetime object


in Python?

# Answer
from datetime import datetime
date_str = "2023-05-12"
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
print(date_obj)
# Output: 2023-05-12 00:00:00

52 All rights reserved InterviewBible.com 2023


85) How do you merge two dictionaries in Python?

# Answer dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} merged_dict


= {**dict1, **dict2} print(merged_dict) # Output: {'a': 1, 'b': 2, 'c':
3, 'd': 4}

86) How do you remove duplicates from a list in


Python?

# Answer
lst = [1, 2, 3, 3, 4, 4, 5]
unique_lst = list(set(lst))
print(unique_lst)
# Output: [1, 2, 3, 4, 5]

87) How do you check if a string is a palindrome in


Python?

# Answer
def is_palindrome(s):
return s == s[::-1]

print(is_palindrome("racecar")) # True
print(is_palindrome("hello")) # False

53 All rights reserved InterviewBible.com 2023


88) How do you reverse a list in Python?

# Answer
lst = [1, 2, 3, 4, 5]
reversed_lst = lst[::-1]
print(reversed_lst)
# Output: [5, 4, 3, 2, 1]

89) How do you flatten a nested list in Python?

You can use a recursive function that checks if each element in the
list is itself a list, and if so, calls the function on that sublist.
Example code:

def flatten(lst):
flat_list = []
for item in lst:
if isinstance(item, list):
flat_list.extend(flatten(item))
else:
flat_list.append(item)
return flat_list

my_list = [1, [2, 3], [4, [

54 All rights reserved InterviewBible.com 2023


90) How do you check if a string contains only digits
in Python?

You can use the isdigit method. Example code:

my_string = "12345"
if my_string.isdigit():
print("The string contains only digits.")
else:
print("The string contains non-digit characters.")

91) How do you sort a list of dictionaries in Python


based on a specific key?

You can use the sorted function with a lambda function that
extracts the value of the key you want to sort on. Example code:

my_list = [ {"name": "Alice", "age": 25},


{"name": "Bob", "age": 30}, {"name": "Charlie", "age": 20}]

sorted_list = sorted(my_list, key=lambda x: x["age"])


print(sorted_list)
# Output: [{"name": "Charlie", "age": 20},
# {"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]

55 All rights reserved InterviewBible.com 2023


92) How do you remove all duplicates from a list in
Python?

You can create a new list with only the unique elements by
converting the original list to a set and then back to a list. Example
code:

my_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
unique_list = list(set(my_list))
print(unique_list) # Output: [1, 2, 3, 4, 5]

93) How do you check if a string contains a specific


substring in Python?

s = "Hello, world!"
if "world" in s:
print("Substring found!")
else:
print("Substring not found.")

56 All rights reserved InterviewBible.com 2023


94) How do you sort a list of strings in alphabetical
order?

a = ["banana", "apple", "cherry"]


a.sort()
print(a)

#Output: ['apple', 'banana', 'cherry']

95) How do you iterate over a dictionary in Python?

d = {"a": 1, "b": 2, "c": 3}


for key, value in d.items():
print(key, value)
a 1
b 2
c 3

96) How do you remove duplicates from a list in


Python?

a = [1, 2, 3, 3, 4, 4, 5]
a = list(set(a))
print(a)
# Output: [1, 2, 3, 4, 5]

57 All rights reserved InterviewBible.com 2023


97) What is the output of the following code?

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

98) How do you reverse a string in Python?

You can reverse a string by slicing it with a step of -1. Example


code:

my_string = "hello world"


reversed_string = my_string[::-1]
print(reversed_string) # Output: "dlrow olleh"

99) How do you find the length of a list in Python?

a = [1, 2, 3, 4, 5]
print(len(a))

# Output: 5

58 All rights reserved InterviewBible.com 2023


100) How do you check if a list is empty in Python?

a = []
if not a:
print("List is empty.")
else:
print("List is not empty.")

101) How do you convert a string to a list of


characters in Python?

s = "hello"
a = list(s)
print(a)

#Output: ['h', 'e', 'l', 'l', 'o']

102) How do you reverse a string in Python?

s = "hello"
s = s[::-1]
print(s)

# Output: olleh

59 All rights reserved InterviewBible.com 2023


103) How do you check if a file exists in Python?

import os
filename = "file.txt"
if os.path.exists(filename):
print("File exists!")
else:
print("File does not exist.")

# Output: File exists!

104) What is a module in Python and how is it


different from a package?

A module in Python is a file containing Python code that can be


imported into other Python programs. A package, on the other
hand, is a collection of modules that are organized in a directory
hierarchy. In other words, a package is a way to organize and
distribute modules in a logical and structured way.

105) What is Python?

Python is a high-level, interpreted programming language that is


used for a wide range of applications, including web development,
data analysis, artificial intelligence, and scientific computing.

60 All rights reserved InterviewBible.com 2023


106) What are the key features of Python?

Some key features of Python include its simplicity, ease of use,


readability, open-source nature, and vast library support.

107) What is PEP 8?

PEP 8 is a set of guidelines for coding in Python that aims to


improve code readability and consistency. It covers things like
indentation, naming conventions, and code structure.

108) How do you declare a variable in Python?

In Python, you can declare a variable by assigning a value to it


using the '=' operator. For example: my_var = 42.

109) What is the difference between a list and a


tuple?

A list is a mutable data structure in Python, which means that its


contents can be changed after it is created. A tuple, on the other
hand, is immutable, meaning that its contents cannot be changed.

61 All rights reserved InterviewBible.com 2023


110) What is a dictionary in Python?

A dictionary in Python is a data structure that stores key-value


pairs. It is similar to a hash table in other programming languages.

111) What is a lambda function in Python?

A lambda function in Python is a small, anonymous function that


can take any number of arguments and return a single value. It is
defined using the 'lambda' keyword, and is often used as a shortcut
for simple functions.

112) What is the difference between '==' and 'is'?

The '==' operator in Python checks whether two objects have the
same value. The 'is' operator, on the other hand, checks whether
two objects are the same object in memory.

62 All rights reserved InterviewBible.com 2023


AT THE END
In this book, we've covered some of the most common Python interview
questions that you might encounter. We've covered a range of topics,
from the basics of Python to more advanced concepts. By studying these
questions and practicing your answers, you'll be well-prepared to ace
your Python interview.

However, keep in mind that during your interview, you may be asked to
solve some other job specific coding challenges or whiteboard problems,
or to discuss your past projects and experience. It's important to be
adaptable and flexible, and to showcase your problem-solving skills and
ability to work collaboratively with others.

Finally, remember that interviews are not just about technical knowledge,
but also about communication and interpersonal skills. Make sure to be
friendly, engaging, and confident, and to listen carefully to your
interviewer's questions and feedback. By doing so, you'll not only
impress your interviewer, but also demonstrate your ability to work well
with others and be a valuable asset to any team.

In conclusion, we hope that this book has been helpful in preparing you
for your Python interview. Remember to stay calm, focused, and
confident, and to showcase your skills and experience to the best of your
ability. With the right preparation and mindset, you'll be well on your way
to landing your dream job as a Python developer. Good luck!

63 All rights reserved InterviewBible.com 2023


PRACTICE & MORE

INTERVIEWBIBLE.COM - A website that provides a collection of


eBooks specifically focused on interview preparation. Our eBooks
cover a variety of fields including technology, business, and more,
providing job seekers with the knowledge and skills needed to excel
in their upcoming interviews. Whether you're looking to brush up on
your interview skills or learn more about specific interview topics,
InterviewBible.com has the resources to help you succeed.
RUBYONRAILS.BA - This place contains collection with more than
6000 links to the other's blogs, tutorials, videos, conferences and
other news.
QUIZ.RUBYONRAILS.BA - This is a place where you can test your
knowledge. The site contains 16 games with different levels and a
collection of more than 500 questions. The site allows you to play
any game for free, and you will be rewarded with a certificate of
completion. You can also challenge your friends to take the same
question set as you and compare your results. In the first two
months, we have already had 150 members on the site with more
than 300 gameplays.
BLOG.RUBYONRAILS.BA - Personal blog, where I share my
thoughts and ideas on a range of topics related to the world of IT,
coding, tutorials, and philosophy. As an experienced developer and
lifelong learner, I am passionate about exploring the latest trends
and technologies in the industry and sharing my insights with
others.

64

You might also like