interview python
interview python
Python is a versatile and widely used programming language, celebrated for its simplicity and
readability. As one of the top choices in the tech industry, Python frequently appears in technical
interviews across various roles, including software development, data science, and automation.
In this guide, we’ll dive into a wide array of Python interview questions and answers, covering
essential topics such as:
These questions are designed to test your grasp of Python's core features, including:
• String Manipulation
• List Operations
• Recursion
Whether you're a beginner just starting your coding journey or an experienced developer brushing
up on your skills, this guide will help you prepare effectively for your next Python interview.
Get ready to boost your confidence and showcase your Python prowess!
Beginner Level
In this section, we cover the basics of Python, which is ideal for those just starting their programming
journey. You'll explore:
• Basic Operations: Learn arithmetic operations, string manipulations, and list handling.
• Simple Functions: Start writing your functions to organize and reuse code.
This level builds a strong foundation, ensuring you're well-prepared to move on to more advanced
topics.
1. What is Python?
Python code is executed line by line at runtime. Python internally converts the source code into an
intermediate form called bytecode, which is then executed by the Python virtual machine (PVM).
• Interpreted language
• Dynamically typed
• Extensive libraries
• Object-oriented
• Portable
4. What is PEP 8?
PEP 8 is the Python Enhancement Proposal that provides guidelines and best practices for writing
Python code. It covers various aspects such as naming conventions, code layout, and indentation.
Python uses automatic memory management and a garbage collector to handle memory. The
garbage collector recycles memory when objects are no longer in use.
try:
except SomeException as e:
import decimal
integer = 10
print(decimal.Decimal(integer))
print(type(decimal.Decimal(integer)))
> 10
import decimal
string = '12345'
print(decimal.Decimal(string))
print(type(decimal.Decimal(string)))
> 12345
print(string[::-1])
word = "programming"
count = 0
if character in vowel:
count += 1
print(count)
>3
word = "programming"
count = 0
count += 1
print(count)
>8
word = "python"
character = "p"
count = 0
if letter == character:
count += 1
print(count)
>1
fib = [0,1]
for i in range(5):
fib.append(fib[-1] + fib[-2])
> 0, 1, 1, 2, 3, 5, 8
maxNum = numberList[0]
maxNum = num
print(maxNum)
> 125
minNum = numberList[0]
print(minNum)
>2
numList = [1, 2, 3, 4, 5]
midElement = int((len(numList)/2))
print(numList[midElement])
>3
string = ''.join(lst)
print(string)
print(type(string))
> PYTHON
lst1 = [1, 2, 3]
lst2 = [4, 5, 6]
res_lst = []
res_lst.append(lst1[i] + lst2[i])
print(res_lst)
> [5, 7, 9]
str1 = "Listen"
str2 = "Silent"
str1 = list(str1.upper())
str2 = list(str2.upper())
str1.sort(), str2.sort()
if(str1 == str2):
print("True")
else:
print("False")
> True
str1 = "Kayak".lower()
str2 = "kayak".lower()
if(str1 == str2[::-1]):
print("True")
else:
print("False")
> True
print(string.count(' '))
>5
import re
print(len(digitCount))
print(len(letterCount))
print(len(spaceCount))
>1
>8
>2
import re
spChar = "!@#$%^&*()"
print(len(count))
> 10
26. Removing All Whitespace in a String
import re
spaces = re.compile(r'\s+')
print(result)
> CODE
floors = 3
h = 2*floors-1
print('{:^{}}'.format('*'*i, h))
> *
***
*****
shuffle(lst)
print(lst)
def find_largest_element(lst):
return max(lst)
# Example usage:
print(find_largest_element([1, 2, 3, 4, 5]))
>5
def remove_duplicates(lst):
return list(set(lst))
# Example usage:
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5]))
> [1, 2, 3, 4, 5]
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
# Example usage:
print(factorial(5))
> 120
> [1, 2, 3, 4, 5, 6]
def first_non_repeating_character(s):
for i in s:
if s.count(i) == 1:
return i
return None
# Example usage:
print(first_non_repeating_character("swiss"))
>w
Advanced Level
In this section, we dive into more complex Python topics, aimed at those looking to deepen their
expertise. You’ll tackle:
• Advanced Data Structures: Work with sets, tuples, and more complex data types.
• Recursion and Iteration: Solve problems using advanced looping and recursive
techniques.
• Modules and Libraries: Leverage powerful Python libraries for various applications.
• Error Handling and Debugging: Learn to write robust code with effective error handling
and debugging techniques.
• Web Scraping and APIs: Gain experience in extracting data from websites and interacting
with APIs.
This level will challenge you to think critically and apply your knowledge to complex problems,
preparing you for high-level Python applications and interviews.
34. What are Python metaclasses?
Metaclasses are classes of classes that define how classes behave. A class is an instance of a
metaclass. They allow customization of class creation.
Python uses reference counting and garbage collection. Objects with a reference count of zero are
automatically cleaned up by the garbage collector.
The with statement simplifies exception handling by encapsulating common preparation and cleanup
tasks in so-called context managers.
data = file.read()
@staticmethod: Defines a method that does not operate on an instance or class; no access to self or
cls.
@classmethod: Defines a method that operates on the class itself; it receives the class as an implicit
first argument (cls).
Using a metaclass
class Singleton(type):
_instances = {}
return cls._instances[cls]
class MyClass(metaclass=Singleton):
pass
Python uses a garbage collection mechanism based on reference counting and a cyclic garbage
collector to detect and collect cycles (groups of objects that reference each other but are not
accessible from any other object).
Magic methods (or dunder methods) are special methods with double underscores at the beginning
and end. They enable the customization of behavior for standard operations
• __init__: Constructor
import threading
def print_numbers():
for i in range(10):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
Coroutines are a type of function that can pause and resume their execution. They are defined
with async def and use await to yield control back to the event loop.
import asyncio
async def say_hello():
await asyncio.sleep(1)
print("Hello")
asyncio.run(say_hello())
44. Explain Python's Global Interpreter Lock (GIL). How does it affect multithreading?
The Global Interpreter Lock (GIL) is a mutex that protects access to Python objects, preventing
multiple native threads from executing Python bytecodes simultaneously in CPython. This lock
simplifies memory management and ensures thread safety but limits the performance of multi-
threaded Python programs by allowing only one thread to execute at a time. As a result, Python
multithreading is more suitable for I/O-bound tasks rather than CPU-bound tasks. Multiprocessing or
other Python implementations like Jython or IronPython may be preferred for CPU-bound tasks.
45. What are metaclasses in Python, and how are they used?
A metaclass in Python is a class of a class that defines how a class behaves. Classes themselves are
instances of metaclasses. You can customize class creation by defining a metaclass, such as modifying
class properties, adding methods, or implementing design patterns. A common use case for
metaclasses is enforcing coding standards or design patterns, such as singleton, or auto-registering
classes.
46. Can you explain the difference between deepcopy and copy in Python?
The copy module in Python provides two methods: copy() and deepcopy().
• copy.copy() creates a shallow copy of an object. It copies the object's structure but not the
elements themselves, meaning it only copies references for mutable objects.
• copy.deepcopy() creates a deep copy of the object, including recursively copying all objects
contained within the original object. Changes made to the deep-copied object do not affect
the original object.
__slots__ is a special attribute in Python that allows you to explicitly declare data members (slots)
and prevent the creation of __dict__, thereby reducing memory overhead. By using __slots__, you
can limit the attributes of a class to a fixed set of fields and reduce the per-instance memory
consumption. This is particularly beneficial when creating a large number of instances of a class.
• == checks for equality, meaning it returns True if the values of the objects are equal, even if
they are different objects in memory.
a = [1, 2, 3]
b=a
c = [1, 2, 3]