Python Top Interview Questions
1.What is PEP 8 and why is it important?
2.What are lists and tuples? What is the key difference between the two?
['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 mutable, tuples 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?
4.What is break, continue and pass in Python?
Break | The break statement terminates the loop immediately and the control flows to the statement after the body of the loop. |
---|---|
Continue | The 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. |
Pass | As 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?
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 theenumerate()
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