Python Interview Questions by Tharun ........................................................................................
Tell me about yourself ? ........................................................................................................... 3
Python-Intro: ............................................................................................................................ 3
Language Fundamentals: .......................................................................................................... 3
DataTypes: ................................................................................................................................ 3
Operators: ................................................................................................................................. 5
Input and output statements: .................................................................................................. 5
Flow control: ............................................................................................................................. 5
Strings: ...................................................................................................................................... 6
List DS: ...................................................................................................................................... 6
Tuple DS: ................................................................................................................................... 6
Set and Frozenset DS: ............................................................................................................... 7
Dict DS:...................................................................................................................................... 7
Functions: ................................................................................................................................. 7
Module and packages: .............................................................................................................. 8
OOPS: ........................................................................................................................................ 8
Exception Handling: ................................................................................................................ 11
Multi-Threading: ..................................................................................................................... 12
File Handling: .......................................................................................................................... 14
Decorators .............................................................................................................................. 16
Generators: ............................................................................................................................. 17
PDBC: ...................................................................................................................................... 18
Logging: ................................................................................................................................... 20
Python Unit Testing: ............................................................................................................... 21
Assertions: .............................................................................................................................. 22
Regular Expression: ................................................................................................................ 23
1|Page
Miscellaneous: ........................................................................................................................ 25
2|Page
Python Interview Questions by Tharun
Tell me about yourself ?
Python-Intro:
1. What is python and its features
2. Why python is interpreter language
3. Difference between python and java
Language Fundamentals:
1. List out the datatypes present in python
2. What is meant by static and dynamic datatypes
3. What is the method used to provide the variable datatypes
DataTypes:
1. Which function is used to get uni-code[ordinance] value
2. Which function is used to get the character of corresponding uni-code val
3. Which function is used to get the length of the string
4. How to access the last index character of a string
5. What is slice operator
6. Can we use string concatenation with other data types like int
7. What is type casting, list out the functions
8. What should be considered while typecasting string literal to other datatypes
like float, int, …. to avoid ValueError
9. What is mutable and immutable
10. What is the purpose of making the datatypes immutable and mutable
3|Page
11. List out the datatypes which are mutable and immutable
12. What are the advantages and disadvantages of immutable nature in datatypes
13. List out the collection related datatypes
14. What is the purpose of using negative index in python
15. In python which datatypes works on indexing concepts
16. What is list in python
17. What is tuple in python
18. What is the difference between list and tuple
19. When to use list and when to use tuple
20. What is set in python
21. What is frozen set in python
22. What is the difference between list and set
23. When to use list when to use set
24. What is the difference between tuple and frozen set
25. When to use tuple when to use frozen set
26. What is dict datatype in python
27. When to use dict datatype
28. What is range datatype in python
29. What is bytes datatype in python
30. What is byte array in python
31. What is None in python
32. Do we have constant in python like java
4|Page
33. Why don’t we have constants in python
Operators:
1. What is the difference between “==” and “is” operator in python
Input and output statements:
Flow control:
1. Give real time example on if condition
2. List out the iterative statements in python
3. What is the difference between "for" and "while" loops in python?
4. What is for each loop in python give one real time example
5. What is while loop in python give one real time example
6. When to use for loop
7. When to use while loop
8. Write a sample code using for loop
9. Write a sample code using while loop
10. How to exit from the loop
11. How to skip from the loop
12. When else block is executed in loops
13. What are transfer statements in python
14. What is break keyword in python
15. What is continue keyword in python
16. What is pass keyword in python
17. What is del keyword in python
5|Page
Strings:
1. What is slice operator in python
2. What is membership operator in python
3. How to check whether the character or string is the member of another string or
not
List DS:
1. Explain me about list ds in python with real time example
2. How many ways we can create a list object
3. How we can access the list elements
4. Tell me some important functions of list
5. What is the differences between append() and insert()
6. What is the differences between remove() and pop()
7. What is the difference between “=” Operator and “copy()” Function
8. What is aliasing and cloning
9. What is List Comprehensions
Tuple DS:
1. Explain me about tuple ds in python with real time example
2. How many ways we can create a tuple object
3. How we can access the tuple elements
4. Tell me some important functions of tuple
5. What is the difference between list and tuple ds
6. Why we don’t have tuple comprehensions like list
6|Page
7. In which scenarios we should go for list and tuple
Set and Frozenset DS:
1. Explain me about set ds in python with real time example
2. Tell me some important functions of set
3. What is the difference between list, tuple, set and frozenset
4. Explain me about frozenset ds in python with real time example
Dict DS:
1. Explain me about dict ds in python with real time example
2. How many ways we can create a dict object
3. How we can access the dict elements
4. What is dictionary Comprehension
Functions:
1. What is function in python
2. List out some built in functions in python
3. What is the use of return keyword in python
1. How many ways we can pass a arguments in function
2. What is Positional Arguments
3. What is Keyword Arguments
4. What is Default Arguments
5. What is Variable Length Arguments
6. Can we use both positional and keyword arguments simultaneously
7. After default arguments can we take non default arguments
7|Page
8. What is local and global variables in python
9. What is the purpose of global keyword in python
10. What is Recursive Functions explain with an real time example
11. What is Anonymous Functions explain with real time example
12. What is the purpose of lambda keyword in python
13. What is filter(), map() and reduce() functions in python
14. What is Function Aliasing
1. What is Nested Functions
2. What is the difference between “f1 = outer” and “f1 = outer()”
3. Can we pass function as argument to another function
Module and packages:
1. What is module in python with example
2. What is Module Aliasing
3. What is special variable __name__ in python
4. What is a package in python
5. What is the purpose of __init__.py file
OOPS:
1. Explain OOPS concepts with real time examples
2. What is Encapsulation, Abstraction, Inheritance and Polymorphism
3. What is the difference between a class and an object?
4. What is a class
5. How to define a Class
8|Page
6. List out the types of variables allowed inside a class
7. What is instance variable
8. What is static variable
9. What is local variable
10. List out the types of methods allowed inside a class
11. What is instance method
12. What is class method
13. What is static method
14. What is Object
15. What is Reference Variable
16. What is Self variable
17. What is constructor in python
18. What is the purpose of the __init__ method?
19. What are differences between methods and constructors
20. What are differences between methods and functions
21. What are difference between instance, class and static methods
22. What are difference between instance, local and static variables
23. What is inner class
24. What are garbage collection and its purpose
25. How to enable and disable Garbage Collector in our Program
26. What are destructors in GC
27. How to find the Number of References of an Object
9|Page
28. In how many ways we can use members of one class inside another class
29. What is composition (Has-A Relationship)
30. What is Inheritance (IS-A Relationship)
31. What are the differences between IS-A and HAS-A Relationship in oops
32. What is composition in oops
33. What is aggregation in oops
34. What are the differences between composition and aggregation
35. Explain me how many types of inheritance we have in oops and python supports
or not
36. What is multiple inheritance, and how is it handled in Python?
37. How Python Handles the Diamond Problem
38. What is MethodResolutionOrder (MRO) or C3 algorithm, how it resolves the
Diamond Problem
39. Explain the concept of decorators and how they are related to OOP.
40. What is super method
41. How to Call Method of a Particular Super Class
42. How to call parent class static method from child class static method by using
super
43. We cannot decide at the beginning what is the type of object and at runtime we
can pass any type. Then how we can decide the Type?
44. What is Duck Typing Philosophy of Python
45. What is the use of hasattr() function.
46. What is overloading and overriding in oops
47. What is operator overloading, does python supports it
10 | P a g e
48. What are magic methods (dunder methods) in Python? Can you give examples?
49. What is method overloading
50. How we can handle Overloaded Method Requirements in Python
51. What is constructor overloading
52. What is Method Overriding
53. What is Abstract Method
54. What is abstract class
55. Can we instantiate a class object with unimplemented abstract methods
56. What is Interfaces In Python
57. What is the difference between concrete class, abstract class and Interface
58. What is Public, Protected and Private Attributes in python
59. How to Access Private Variables from Outside of the Class:
60. What is name mangling in python
61. What is the Singleton design pattern? How can it be implemented in Python?
62. How is abstraction achieved in Python?
Exception Handling:
1. What is exception
2. What is exception handling
3. What errors we can expect while writing code
4. What is syntax error
5. What is runtime error or exceptions
6. What is Default Exception Handing in Python
11 | P a g e
7. What is Python's Exception Hierarchy
8. How we can customize Exception Handling in python
9. What is finally
10. How many types of Exceptions are there in python
11. What are Predefined Exceptions
12. What are User Defined Exceptions
13. Tell me any real-time example for User Defined Exceptions
14. How to Define and Raise Customized Exceptions
Multi-Threading:
1. What is thread explain with an real-time example
2. How we can print Name of Current executing Thread
3. How many ways we can create a thread in Python
4. Can we get or set the thread name
5. What function will be used to know the number of current threads executing
6. What function will be used if you want to know the list of all active threads
currently running.
7. What function will be used to check whether a thread is still executing or not
8. What is Thread Identification Number
9. What is join() Method:
10. What is Daemon Threads
11. How we can check whether thread is Daemon or not
12. How we can change Daemon nature of thread, what we have to consider before
changing
12 | P a g e
13. In which scenario we can’t change the daemon nature of thread
14. Why Main Thread is always Non-Daemon and we cannot change its Daemon
Nature
15. When all Daemon Threads will be terminated.
16. What is Synchronization in multithreading
17. What are the advantages and disadvantages of synchronization in python
18. How many ways we can implement synchronization in python
19. How we implement synchronization using Lock concept
20. Is there any drawbacks in using Lock concept in synchronization
21. How we implement synchronization using RLock(Reentrant Lock) concept
22. Is there any drawbacks in using RLock concept in synchronization
23. How we implement synchronization using Semaphore concept
24. We have already lock concept for synchronization again what is the need of
RLock concept
25. We have already lock and RLock concept for synchronization again what is the
need of Semaphore concept
26. What is the difference between Lock and RLock in synchronization
27. In which scenario we should go for Lock, RLock and Semaphore concepts in
synchronization
28. What is Bounded Semaphore
29. What is the difference between Lock and Semaphore
30. What is Inter Thread Communication in multithreading
31. How we can implement inter-thread communication in python
13 | P a g e
32. Explain me the implementation of Inter Thread Communication by using Event
Object
33. Explain me the implementation of Inter Thread Communication by using
Condition Object
34. Explain me the implementation of Inter Thread Communication by using Queue
35. What Types of Queues supported in python
36. What are the good Programming Practices while using the Locks concepts
multithreading
37. What is the Advantage of using with Statement to acquire a Lock in Threading?
File Handling:
Basic File Handling Questions:
1. What is file handling in Python?
2. How do you open a file in Python? Explain the modes used to open files (read,
write, append, etc.).
3. What are the differences between 'r', 'w', 'a', 'rb', and 'wb' modes in Python?
4. How do you read data from a file in Python? Explain different methods (read(),
readline(), readlines()).
5. How do you write data to a file in Python? Explain the usage of write() and
writelines() methods.
6. What is the purpose of the with statement in file handling?
7. How do you close a file in Python, and why is it important to do so?
8. What is the difference between open() and with open() in Python?
Intermediate File Handling Questions:
9. How would you handle exceptions when working with files in Python?
10. How can you check if a file exists before opening it?
11. Write a Program to check whether the given File exists OR not. If it is available
then print its content?
12. Write a Program to print the Number of Lines, Words and Characters present in
the given File
14 | P a g e
13. What is the difference between text files and binary files in Python? How do you
handle binary files?
14. How do you move the file pointer to a specific location in a file (using seek())?
15. How can you get the current position of the file pointer (using tell())?
16. Explain how to delete a file or rename a file in Python.
17. How can you copy the contents of one file to another in Python?
18. How do you read or write large files efficiently in Python?
Advanced File Handling Questions:
19. What is file buffering in Python, and how can you control it?
20. How do you work with file paths in a cross-platform manner using Python
(using os and pathlib modules)?
21. How do you handle file encoding in Python? How do you read and write files in
different encodings?
22. What are memory-mapped files, and how do you use them in Python?
23. Explain how to read or write compressed files (e.g., .gz, .zip) in Python.
24. How do you handle file operations using asynchronous methods in Python?
25. How can you ensure that a file is locked while being read or written to (file
locking)?
26. What is the shutil module used for in file handling?
Working with Directories:
27. How to Know Current Working Directory
28. How to Create a Sub Directory in the Current Working Directory
29. How to Create a Sub Directory in mysub Directory
30. How To Create Multiple Directories like sub1 in that sub2 in that sub3
31. How To Remove a Directory
32. How To Remove Multiple Directories in the Path
33. How To Rename a Directory
34. How To know Contents of Directory
35. How To Know Contents of Directory including Sub Directories
36. What is the difference between listdir() and walk() Functions?
37. How to Run Other Programs from Python Program
38. How to get Information about a File:
15 | P a g e
39. How To Print all Statistics of File [Link]
40. How To Print specified Properties
Decorators
Basic Questions:
1. What is a decorator in Python
2. How to define a decorator and apply it to a function using the @decorator_name
syntax.
3. Explain the concept of a decorator and how it modifies the behaviour of a
function or method in Python.
4. How do decorators work in Python
5. Can you explain the difference between a decorator and a higher-order
function?
6. Can you explain function and method decorators with an example
7. Can decorators accept arguments? How would you implement one
Intermediate Questions:
8. How can you pass arguments to a decorator?
9. How do decorators handle functions with arguments
10. how a decorator can be written to handle functions that accept arguments and
return values
11. What is the [Link] function, and why is it important in decorators
12. Explain how [Link] helps preserve the metadata (like name,
docstring) of the original function when it is wrapped by a decorator.
13. Can a function have multiple decorators applied? How is the execution order
determined?
14. Explain how you can stack multiple decorators and the order in which they are
applied
15. What are some common use cases for decorators in Python
16. How to call Same Function with Decorator and without Decorator
16 | P a g e
Advanced Questions:
17. How would you implement a class-based decorator
18. Explain how to implement a decorator using a class instead of a function, and
when you might use this approach
19. Can decorators be used on classes? How would you implement one
20. Can decorators be used with methods in classes
21. Explain how decorators work with instance methods and how self is passed to the
wrapper function.
22. What are the key differences between function decorators and class decorators
23. How would you implement a decorator to cache the results of a function
24. How would you implement a decorator to enforce type-checking in Python
Generators:
Basic Questions
1. What is a generator in Python?
2. What are the advantages of Generator Functions
3. Explain how generators differ from regular functions.
4. How do you create a generator in Python?
5. What are the key differences between yield and return in Python?
6. Explain what happens when yield is used in a function.
7. How can you convert a generator into a list?
8. What are the performance implications of doing so?
9. What happens if you try to call next() on a generator that has no more values to
yield? How would you handle such a situation?
Advanced Questions
10. How does a generator differ from a normal iterator or an iterable object?
11. Explain the advantages of using a generator over other iterables.
12. What are generator expressions in Python, and how are they different from list
comprehensions?
13. Can you give an example where a generator expression would be more efficient
than a list comprehension?
14. Explain how you would create an infinite generator.
17 | P a g e
15. How can you terminate or limit the output of an infinite generator?
16. Can you pass arguments into a generator function?
17. Provide an example where arguments are passed to control the flow inside a
generator.
Real-world Use Cases
18. When would you use a generator in a real-world application?
19. Can you explain scenarios where generators are preferred due to memory
efficiency or laziness in evaluation?
20. How would you use a generator to read a large file line by line in Python?
21. What are the memory benefits of doing this?
22. How to debug generators?
Performance and Limitations
23. Discuss the memory efficiency of generators.
24. How do generators help in handling large datasets or streams?
25. What happens to the local variables inside a generator after each yield?
26. Can a generator remember its state between yields?
27. Can you use multiple yield statements in a generator function?
28. Provide an example demonstrating how multiple yields work inside a single
function.
29. What are the limitations of Python generators?
30. When would you avoid using generators?
Code-based Questions
31. Write a generator that returns the Fibonacci sequence up to a given number.
32. Implement a generator that yields the square of numbers from 1 to 10.
33. Write a generator that yields prime numbers indefinitely.
PDBC:
Basic Questions:
1. What is a database?
2. Explain what a database is and its purpose.
3. What is the sqlite3 module in Python?
18 | P a g e
4. How do you use sqlite3 for database connectivity?
5. How do you connect to a MySQL database in Python?
6. What libraries or packages are used for connecting Python to a MySQL
database?
7. What is the psycopg2 module in Python?
8. How do you use psycopg2 for database connectivity?
9. How do you connect to a PostgreSQL database in Python?
10. What libraries or packages are used for connecting Python to a PostgreSQL
database?
11. What is the difference between commit() and rollback() in database
transactions?
12. Explain their purposes in database transactions.
13. What are database cursors in Python?
14. How does the cursor help in executing queries and fetching results?
15. How do you execute an SQL query in Python?
16. Provide examples of executing SELECT, INSERT, UPDATE, and DELETE
statements.
17. What is a parameterized query in Python?
18. Explain its importance in preventing SQL injection attacks and give an example
of a parameterized query in Python.
19. What are the common database exceptions in Python?
20. How do you handle exceptions like IntegrityError, OperationalError, etc.?
Intermediate Questions:
21. What is the role of a connection pool in Python database connectivity?
22. Why would you use a connection pool, and how do you implement one?
23. How do you manage database transactions in Python?
24. Explain how you manage multi-step transactions using Python.
25. What is the difference between fetchone(), fetchall(), and fetchmany() methods
in Python?
26. When would you use each?
27. Explain how to use pandas for database interaction in Python.
28. How can you convert a SQL query result into a DataFrame?
19 | P a g e
29. How would you prevent SQL injection in a Python program?
30. Give examples of safe coding practices.
Advanced Questions:
Explain how to handle concurrent database access in Python.
How do you handle multi-threaded or multi-process database access?
What are some ways to optimize database queries in Python?
Discuss the use of indexes, query caching, and connection optimization.
How would you set up a Python application to work with multiple databases?
Discuss how to connect to and manage multiple databases simultaneously.
What is the difference between ORM and direct SQL queries in Python?
Explain when to use Object-Relational Mapping (e.g., SQLAlchemy, Django ORM) vs.
raw SQL queries.
How do you ensure database security in a Python application?
Discuss secure practices for handling credentials, database access, and
connections.
Logging:
Basic Logging Concepts:
1. What is logging in Python, and why is it used?
2. Explain the basic components of the logging module in Python.
3. What are the standard logging levels in Python?
4. How do you configure basic logging in Python?
Advanced Logging Configuration:
5. How can you log messages to a file instead of the console?
6. What is a logger object, and how do you create one?
7. How can you add multiple handlers to a logger?
8. How can you add multiple handlers to a logger?
9. How do you log an exception in Python?
Real-world Scenarios:
10. How would you log different modules in a large application?
11. What are Rotating File Handlers, and why are they used?
20 | P a g e
12. How can you avoid duplicate log entries when adding multiple handlers?
13. How can you change the log level dynamically at runtime?
14. How do you filter specific log messages (e.g., by level or content)?
15. What is the difference between [Link]() and [Link]()?
16. How do you disable logging?
Python Unit Testing:
Basic Concepts:
1. What is unit testing and why is it important in software development?
2. What is the purpose of the unittest module in Python?
3. Explain the concept of test fixtures. How are they used in Python unit tests?
4. What is the difference between a unit test and an integration test?
5. Can you explain the role of setUp() and tearDown() methods in unit testing?
Practical Python Unit Testing:
6. How would you write a simple unit test using Python’s unittest framework?
7. How can you run a subset of tests using the unittest framework?
8. How do you handle exceptions in Python unit tests?
9. How can you assert that an exception is raised in Python's unittest?
10. Explain the difference between assertEqual(), assertTrue(), assertFalse(), and
assertRaises() in Python unit tests.
Advanced Unit Testing:
11. What are mocks in unit testing, and how would you implement them using
Python’s [Link] module?
12. Can you explain the difference between Mock(), MagicMock(), and patch() in the
[Link] module?
13. How would you mock an external API call in a Python unit test?
14. How do you test private methods in Python?
15. Explain the purpose and usage of side_effect and return_value in [Link].
Test Automation & Best Practices:
16. How do you ensure your unit tests are maintainable and easy to read?
17. What are the best practices for writing unit tests in Python?
21 | P a g e
18. How would you organize test cases in a large Python project?
19. What are some common mistakes developers make while writing unit tests, and
how can they be avoided?
20. How do you integrate Python unit tests with a continuous integration or
continuous deployment (CI/CD) pipeline?
Miscellaneous:
21. What is test-driven development (TDD), and how does it influence unit testing?
22. How do you handle dependencies between unit tests in Python?
23. Explain how to test for performance in Python using unit tests.
24. What are parameterized tests in Python, and how can you implement them in
unittest?
25. What is code coverage, and how do you measure it for Python unit tests?
Assertions:
Basic Questions:
1. What are assertions in Python, and why are they used?
2. How do you write a simple assertion in Python?
3. What happens when an assertion fails in Python?
4. What is the difference between assert and raise in Python?
Intermediate Questions:
5. Can assertions be disabled in Python? If so, how
6. Explain the difference between a try-except block and using assertions.
7. What is the purpose of the optional error message in an assertion?
8. Is it good practice to use assertions for input validation in production code?
Why or why not?
Advanced Questions
9. How do assertions work internally in Python?
[Link] you catch an assertion error? How would you handle it in Python?
[Link] an example where assertions can be useful in test-driven development
(TDD)
[Link] do assertions interact with unittest in Python?
22 | P a g e
[Link] is the performance implication of using assertions in performance-critical
applications?
Scenario-based Questions
[Link] have a function that processes a list. You expect the list to always contain
more than 3 elements. How would you use assertions to validate this
assumption?
[Link] assertions be used for ensuring type safety in Python? If so, how?
Regular Expression:
Basic Questions
What is a regular expression?
Explain the concept of regex and its uses in pattern matching, searching, and manipulating
strings.
How do you import the re module in Python?
What are some common functions provided by the re module?
Discuss functions like search(), match(), findall(), finditer(), sub(), and split().
What is the difference between search() and match()?
search() scans through a string and looks for any location where the regex pattern
produces a match; match() checks for a match only at the beginning of the string.
Intermediate Questions
How can you use regex to validate an email address?
Provide a regex pattern for matching email addresses and explain its components.
What is the purpose of the [Link]() function?
Discuss how it can be used to compile a regex pattern into a regex object for reuse.
Explain the difference between greedy and non-greedy matching.
Describe how greedy matching consumes as much of the input as possible, while non-
greedy matching consumes the least amount.
How do you handle special characters in regex patterns?
Explain the use of escape sequences (e.g., \) for special characters like . and *.
23 | P a g e
Advanced Questions
What are capturing groups and how do they work?
Explain how parentheses () are used to create capturing groups and how to access them.
How would you replace all occurrences of a word in a string using regex?
Use the sub() function and provide an example.
Can you explain what lookaheads and lookbehinds are?
Discuss the concepts of positive and negative lookaheads and lookbehinds with examples.
How can you use regex to extract specific information from a log file?
Provide an example regex pattern to extract timestamps, error codes, or other relevant
information from log data.
Practical Questions
Write a regex pattern to match a valid URL.
Discuss the components of the regex and provide a sample implementation.
Given a string, how would you check if it contains only digits?
Use [Link]() or [Link]() with the appropriate pattern.
How would you split a string by multiple delimiters using regex?
Use the [Link]() function with a regex pattern that matches multiple delimiters.
Write a regex to find all the words that start with a capital letter in a string.
Provide the regex pattern and explain how it works.
Scenario-Based Questions
You have a string containing dates in various formats (e.g., MM-DD-YYYY,
YYYY/MM/DD). How would you extract all dates?
Discuss creating a regex pattern that captures both formats.
How would you use regex to validate a password that must contain at least one
uppercase letter, one lowercase letter, one digit, and one special character?
Provide an example regex pattern and explain the components.
Given a text file, how would you count the number of times a specific word appears
using regex?
Explain reading the file, using [Link](), and counting the occurrences.
24 | P a g e
How would you implement a simple search-and-replace function using regex in
Python?
Provide an example implementation using [Link]().
Miscellaneous:
1. What is shallow copy & deep copy explain it with example
2. What is Pydoc-Python Documentation Tool
25 | P a g e