Python top interview questions

Written by recentjobs.in

Published on:

Youtube Channel Subscribe Now
Instagram Page Follow Me
Telegram Group Join Now
whatsapp Group Join Group

Python Top Interview Questions

1.What is PEP 8 and why is it important?

PEP stands for Python Enhancement Proposal. A PEP is an official design document providing information to the Python community, or describing a new feature for Python or its processes. PEP 8 is especially important since it documents the style guidelines for Python Code. Apparently contributing to the Python open-source community requires you to follow these style guidelines sincerely and strictly.

2.What are lists and tuples? What is the key difference between the two?

Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets ['guna', 6, 0.19], while tuples are represented with parantheses ('sun', 5, 0.97).
But what is the real difference between the two? The key difference between the two is that while lists are mutabletuples on the other hand are immutable objects. This means that lists can be modified, appended or sliced on the go but tuples remain constant and cannot be modified in any manner.

3.What is the use of self in Python?

Self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. self is used in different places and often thought to be a keyword. But unlike in C++, self is not a keyword in Python.

4.What is break, continue and pass in Python?

BreakThe break statement terminates the loop immediately and the control flows to the statement after the body of the loop.
ContinueThe continue statement terminates the current iteration of the statement, skips the rest of the code in the current iteration and the control flows to the next iteration of the loop.
PassAs explained above, the pass keyword in Python is generally used to fill up empty blocks and is similar to an empty statement represented by a semi-colon in languages such as Java, C++, Javascript, etc.

5.What is the difference between a Mutable and an Immutable data type?

Mutable data types are those whose values can be changed after they are created, while immutable data types are those whose values cannot be changed after they are created.

Here’s a more detailed breakdown:

Mutable Data Types:

  • Mutable data types can be edited, meaning their values can change during runtime.
  • Examples include lists, dictionaries, and sets.
  • For example, you can modify elements in a list, add or remove items from a dictionary, or change the values of elements in a set.

Immutable Data Types:

  • Immutable data types cannot be edited, meaning their values cannot change once they are created.
  • Examples include strings, tuples, and frozen sets.
  • For example, you cannot change the characters in a string, modify elements in a tuple, or alter the items in a frozen set after they have been created.

6.What is the difference between a Set and Dictionary?

Set:

  • A set is an unordered collection of unique elements.
  • It is iterable, mutable, and does not allow duplicate elements.
  • Sets are created using curly braces {}, and elements are separated by commas.
  • Sets are primarily used for mathematical operations like union, intersection, difference, etc.

Dictionary:

  • A dictionary is an unordered collection of key-value pairs.
  • It is iterable and mutable but does not allow duplicate keys.
  • Dictionaries are created using curly braces {}, with key-value pairs separated by colons : and individual pairs separated by commas.
  • Dictionaries are often used to store data in the form of key-value pairs, where each value is accessed by its corresponding key.
  • Unlike sets, dictionaries have a specific association between keys and values, making them useful for representing structured data.

7.What is List Comprehension? Give an Example.

List comprehension is a concise syntax in Python used to create lists from existing iterables or sequences. It provides an easy and readable way to generate lists in a single line of code.

For example:

my_list = [i for i in range(1, 10)]

This line of code generates a list containing numbers from 1 to 9. It iterates over the range from 1 to 10 (excluding 10) and appends each number to the list.

List comprehensions can also include conditions:

even_numbers = [i for i in range(1, 10) if i % 2 == 0]

This code creates a list of even numbers by filtering out odd numbers from the range.

8.How is Exceptional handling done in Python?

Exception handling in Python is managed primarily through three keywords: try, except, and finally.

  • try block: This is where you put the code that might raise an exception. It’s like a test zone. If an error occurs in this block, Python looks for an except block to handle it.
  • except block: This block catches and handles exceptions that occur in the try block. You can have multiple except blocks to handle different types of exceptions. If an error occurs in the try block, the code inside the except block is executed.
  • finally block: This block is optional. It’s used for cleanup activities that should be executed regardless of whether an exception occurred or not. For example, closing a file or releasing a network connection.

Here’s a simple example:

python

try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError:
# Handle the specific exception
print("Cannot divide by zero!")
finally:
# Clean up code, executed whether an exception occurred or not
print("Done with exception handling.")

This would output:

csharp

Cannot divide by zero!
Done with exception handling.

The try block attempts to execute the code 10 / 0, which raises a ZeroDivisionError. The except block catches this exception and prints a message. Then, regardless of the exception, the finally block prints a cleanup message.

9.What is a break, continue, and pass in Python?

  • break statement: This statement is used to terminate the loop or statement it is present in. When a break statement is encountered inside a loop, the loop is immediately terminated, and the control flows to the next statement after the loop.
  • continue statement: Unlike break, the continue statement does not terminate the loop. Instead, it skips the rest of the code inside the loop for the current iteration and jumps to the next iteration of the loop.
  • pass statement: The pass statement is used as a placeholder in situations where Python syntax requires a statement but no action is needed. It’s like saying “do nothing”. It’s often used when the syntax requires a statement but the programmer intends to do nothing.

Here’s an example to illustrate these statements:

for i in range(1, 6):
if i == 3:
print(“Encountered 3, breaking loop”)
break
print(“Current value:”, i)
OUTPUT:
Current value: 1
Current value: 2
Encountered 3, breaking loop

for i in range(1, 6):
if i == 3:
print(“Encountered 3, skipping this iteration”)
continue
print(“Current value:”, i)

OUTPUT:

Current value: 1
Current value: 2
Encountered 3, skipping this iteration
Current value: 4
Current value: 5

for i in range(1, 6):
if i == 3:
print(“Encountered 3, using pass”)
pass
print(“Current value:”, i)

OUTPUT:

Current value: 1
Current value: 2
Encountered 3, using pass
Current value: 3
Current value: 4
Current value: 5

10.Differentiate between List and Tuple?

List:

  • Mutability: Lists are mutable, meaning their elements can be changed after the list is created.
  • Memory consumption: Lists consume more memory compared to tuples due to their mutable nature.
  • Performance: Lists are better for performing operations like insertion and deletion because they can be modified in place.
  • Iteration: Iterating through lists might be slower, especially with large datasets, due to their mutable nature and potential resizing.

Tuple:

  • Immutability: Tuples are immutable, meaning their elements cannot be changed after the tuple is created.
  • Memory consumption: Tuples consume less memory compared to lists because they are immutable.
  • Accessing elements: Tuples are appropriate for accessing elements directly because of their immutability.
  • Iteration: Iterating through tuples is generally faster than lists, especially with large datasets, due to their immutability and fixed size.

Both lists and tuples have their advantages and use cases. Lists are preferred when you need a collection of items that can change over time, while tuples are useful when you want to ensure data integrity and prevent accidental modifications.

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

Shallow Copy:

  • A shallow copy creates a new object but does not create copies of nested objects. Instead, it references the nested objects from the original object.
  • Changes made to the nested objects in the shallow copy will reflect in the original object, and vice versa.
  • Shallow copies are faster to create and use less memory compared to deep copies.

Deep Copy:

  • A deep copy creates a new object and recursively creates copies of nested objects, so changes made to the nested objects in the deep copy will not affect the original object, and vice versa.
  • Deep copies are slower to create and use more memory compared to shallow copies, especially when dealing with large or complex objects.

Here’s a bit more detailed example to illustrate:

import copy

# Original list
original_list = [[1, 2, 3], [4, 5, 6]]

# Shallow copy
shallow_copied_list = copy.copy(original_list)

# Deep copy
deep_copied_list = copy.deepcopy(original_list)

# Modifying the nested list in shallow copy
shallow_copied_list[0][0] = 100

# Modifying the nested list in deep copy
deep_copied_list[0][0] = 1000

print(“Original list:”, original_list)
print(“Shallow copied list:”, shallow_copied_list)
print(“Deep copied list:”, deep_copied_list)

OUTPUT:

Original list: [[100, 2, 3], [4, 5, 6]]
Shallow copied list: [[100, 2, 3], [4, 5, 6]]
Deep copied list: [[1000, 2, 3], [4, 5, 6]]

12.What are the different ways to iterate over a list in Python?

  • You can iterate over a list using a for loop, list comprehension, or the enumerate() function.
  • For example:

for item in my_list:
print(item)

# Using list comprehension
new_list = [x*2 for x in my_list]

# Using enumerate()
for index, item in enumerate(my_list):
print(index, item)

13.What is the difference between '==‘ and ‘is' in Python?

The == operator checks for equality of values, while the is operator checks for identity (whether two objects refer to the same memory location).

For example:

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True, because values are the same
print(a is b) # False, because they are different objects

14.What is a decorator in Python?

A decorator is a design pattern in Python that allows you to modify the behavior of a function or class. It is implemented using functions or classes that wrap other functions or classes. Decorators are commonly used for logging, authentication, and memoization.

15.Explain the concept of *args and kwargs in Python.

*args and **kwargs allow functions to accept a variable number of arguments. *args collects positional arguments into a tuple, while **kwargs collects keyword arguments into a dictionary.

For example:

def my_function(*args, **kwargs):
print(args) # Tuple of positional arguments
print(kwargs) # Dictionary of keyword arguments

my_function(1, 2, a=3, b=4)

16.What is a lambda function in Python?

A lambda function is a small, anonymous function defined using the lambda keyword. It can take any number of arguments but can only have one expression. Lambda functions are commonly used for short, simple operations.

add = lambda x, y: x + y
print(add(2, 3)) # Output: 5

17.What is a generator in Python?

A generator is a special type of iterator in Python that generates values on the fly using the yield keyword. Generators are memory-efficient and allow you to iterate over large datasets without loading the entire dataset into memory.

18.How does Python’s garbage collection work?

Python’s garbage collector automatically deallocates memory for objects that are no longer referenced. It uses reference counting and a cyclic garbage collector to reclaim memory. Reference counting keeps track of the number of references to an object, and when the count drops to zero, the object is deallocated. The cyclic garbage collector identifies and collects cyclic references that cannot be detected by reference counting.

Python top interview questions:

Top 10 Coding Interview Questions:

1.Reverse a String:

Write a function to reverse a given string.

For example, if the input is “hello”, the output should be “olleh”.

def reverse_string(s):
return s[::-1]

2.Check Palindrome:

Write a function to check if a given string is a palindrome. For example, if the input is “radar”, the output should be True.

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

3.Check Anagram:

Write a function to check if two given strings are anagrams of each other.

For example, “listen” and “silent” are anagrams.

def is_anagram(s1, s2):
return sorted(s1) == sorted(s2)

4.Find the Missing Number:

Given a list of integers from 1 to n with one number missing, find the missing number.

def find_missing_number(nums):
n = len(nums) + 1
total = n * (n + 1) // 2
return total – sum(nums)

5.Reverse a Linked List:

Write a function to reverse a singly linked list.

class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

def reverse_linked_list(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev

6.Check Balanced Parentheses:

Write a function to check if a given string containing parentheses is balanced.

def is_balanced(s):
stack = []
for char in s:
if char in ‘([{‘:
stack.append(char)
else:
if not stack or stack.pop() != ‘([{‘.index(char):
return False
return not stack

7.Two Sum:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target – num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return None

8.Find the Maximum Subarray:

Given an integer array, find the contiguous subarray with the largest sum.

def max_subarray(nums):
max_sum = current_sum = nums[0]
for num in nums[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum

9.Fibonacci Sequence:

Write a function to generate the Fibonacci sequence up to n terms.

def fibonacci(n):
fib = [0, 1]
while len(fib) < n:
fib.append(fib[-1] + fib[-2])
return fib[:n]

10.Remove Duplicates from a List:

Write a function to remove duplicates from a list while preserving the original order of elements.

def remove_duplicates(nums):
seen = set()
result = []
for num in nums:
if num not in seen:
result.append(num)
seen.add(num)
return result

OUTPUT:

nums = [1, 3, 2, 1, 5, 2, 6, 7, 8, 7, 4]
print(remove_duplicates(nums)) # Output: [1, 3, 2, 5, 6, 7, 8, 4]

For More Interview Tips and Questions : Click Here

For Job Alerts : Click Here

For any doubts Ping me : Click Insta

Leave a Comment