Top Python Interview Questions (2023)

Python interview questions can vary depending on the specific role and company, but some common topics include data types, control structures, functions, classes and objects, modules, file I/O, and libraries such as NumPy, Pandas, and Flask. It's also common for interviewers to ask about best practices, debugging techniques, and problem-solving skills. It's important to have a strong understanding of Python fundamentals and to be able to demonstrate your ability to write clear, efficient, and maintainable code.

What is Python?

Python is a high-level, interpreted programming language that was first released in 1991. It is designed to be easy to read and write, with a simple and expressive syntax that emphasizes code readability. Python is widely used for a variety of applications, including web development, scientific computing, data analysis, artificial intelligence, and automation. It has a large and active community of developers, a vast array of third-party libraries and tools, and runs on multiple platforms, including Windows, macOS, and Linux.

What type of language is python? Programming or scripting?

Python is both a programming language and a scripting language. As a programming language, it can be used to create complex software applications with a wide range of functionalities. As a scripting language, it can be used to write scripts that automate tasks, such as file operations and system management, and can be executed without the need for a compiler. Python's flexibility and versatility make it a popular choice for both programming and scripting purposes.

What are the key features of Python?

Some of the key features of Python include:

  1. Simple and easy-to-learn syntax
  2. Interpreted language, meaning it does not require compilation
  3. Dynamically typed, meaning the data type is determined at runtime
  4. Strong support for object-oriented programming
  5. Large and active community of developers and users
  6. Rich standard library with a wide range of modules and functions
  7. Cross-platform support for Windows, macOS, and Linux
  8. Integration with other programming languages, such as C and C++
  9. Third-party libraries and tools for a wide range of applications, such as web development, data analysis, and artificial intelligence.

What is Python good for?

Python is good for a wide range of applications, including:

  1. Web development: Python can be used for server-side web development with frameworks such as Django and Flask.
  2. Data analysis and visualization: Python has a rich set of libraries such as NumPy, Pandas, and Matplotlib, which make it a popular choice for data analysis and visualization.
  3. Scientific computing: Python has powerful libraries such as SciPy, SymPy, and Biopython, which make it a great choice for scientific computing.
  4. Artificial intelligence and machine learning: Python has a variety of powerful libraries and frameworks such as TensorFlow, Keras, and PyTorch, making it a top choice for AI and machine learning.
  5. Automation and scripting: Python's easy-to-learn syntax and rich set of libraries make it a great choice for automation and scripting tasks, such as system management and file operations.
  6. Education: Python's simple syntax and rich set of libraries make it a great choice for beginners to learn programming.

Python's versatility, ease of use, and wide range of applications make it a popular choice for developers and users.


Python Interview Questions and Answers

Is Python platform independent?

Yes, Python is platform independent. It can be used on multiple platforms, including Windows, macOS, and Linux, without the need for changes to the code. Python's interpreter and standard library are written in C, which makes it possible for Python code to run on any platform that has a Python interpreter installed. This cross-platform compatibility makes Python a popular choice for developers who want to create software that can run on multiple operating systems.

Is Python case-sensitive?

Yes, Python is platform independent, which means that Python code can run on different platforms, such as Windows, macOS, and Linux, without requiring any modification. This is because Python is an interpreted language and uses an interpreter to execute code, rather than requiring a separate compilation step for each platform. Additionally, many third-party libraries and tools that are commonly used with Python are also platform independent, making it easier to develop and distribute Python applications across different platforms.

What is Scope in Python?

Scope in Python refers to the region of the program where a particular variable is accessible or visible. Python has two main types of scopes:

  1. Global scope: Variables that are defined outside of any function or class have global scope, which means they are accessible throughout the program.
  2. Local scope: Variables that are defined inside a function or a class have local scope, which means they are only accessible within that function or class.
Python uses the "LEGB" rule to determine the scope of a variable: Local, Enclosing, Global, and Built-in. This means that Python will first look for a variable in the local scope, then in any enclosing functions or classes, then in the global scope, and finally in the built-in scope, which contains functions and variables that are available by default in Python. Understanding scope is important in Python programming because it helps avoid naming conflicts and ensures that variables are used in the appropriate context.

How would you define a block of code in Python?

In Python, a block of code is defined as a group of statements that are indented to the same level. The indentation level determines which statements are included in the block. In Python, the standard indentation is four spaces or one tab. Here's an example of a simple block of code that prints a message:
if x > 10: print("x is greater than 10")
In the above example, the block of code consists of a single print statement, which is indented to the same level as the if statement. The if statement is used to test whether the variable x is greater than 10. If the condition is true, the print statement is executed. The indentation is important in Python because it helps to define the structure of the code and ensures that the program behaves as intended.

What is the purpose of PYTHONSTARTUP environment variable?

The PYTHONSTARTUP environment variable is used to specify the path to a Python script that will be executed every time the Python interpreter is started. The script can contain any valid Python code, such as import statements or function definitions, and it will be executed before the interactive console is displayed. This is useful for setting up a customized Python environment, such as importing commonly used modules, defining aliases for frequently used commands, or initializing global variables. By setting the PYTHONSTARTUP environment variable to the path of a startup script, these customizations can be automatically applied every time the Python interpreter is launched, saving time and reducing the need to manually enter repetitive commands.

What is lambda in Python?

In Python, a lambda function is a small, anonymous function that can be defined without a name. It is a single expression that can take any number of arguments, and returns the value of the expression. The syntax for defining a lambda function is:
lambda arguments: expression

For example, the following code defines a lambda function that adds two numbers together:

add = lambda x, y: x + y

This lambda function can be called like any other function:

result = add(3, 5) print(result) # Output: 8
Lambda functions are often used as a shorthand for defining simple functions that are only used once. They can be used in place of named functions and passed as arguments to other functions.

What is self in Python?

In Python, "self" is a reference to the instance of a class. It is a common convention to use "self" as the first parameter of a method in a class, and it refers to the instance of the class that the method is being called on. Using "self" is an important aspect of object-oriented programming in Python, as it allows you to access the state and behavior of an instance of a class from within the class methods.

What is slicing?

In Python, slicing is a technique for extracting a portion of a sequence (a list, tuple, or string) by specifying a start and end index. The resulting slice contains all elements in the original sequence between the start and end index, including the element at the start index but excluding the element at the end index.

The syntax for slicing is:

sequence[start:end]

Slicing is a powerful technique in Python that allows you to extract and manipulate portions of sequences with ease.

What is a dynamically typed language?

A dynamically typed language is a programming language in which the data types of variables are determined at runtime, rather than at compile time. This means that the type of a variable can change during the execution of a program, based on the value that is assigned to it. In a dynamically typed language, the data type of a variable is inferred from the value it holds, and the language automatically performs any necessary type conversions when operations are performed on the variable. This allows for more flexibility and faster development, as programmers do not need to explicitly declare the data type of each variable. Python is an example of a dynamically typed language, as the type of a variable is determined based on the value assigned to it. For example, the following code is valid in Python:
x = 42 x = "hello"
In the above example, the variable "x" is first assigned the integer value 42, and then later reassigned the string value "hello". In a statically typed language, this would not be allowed, as the type of "x" would be fixed at compile time. However, in Python, the type of "x" is determined dynamically at runtime, based on the value that is assigned to it.

What is __init__?

In Python, __init__ is a special method that is called when an object is created from a class. It is used to initialize the attributes of the object, and can take arguments to set the initial values of those attributes. The __init__ method is defined in the class, and takes the self parameter as the first argument, which refers to the object being created. Any additional parameters passed to the method are used to initialize the attributes of the object.

How is memory managed in Python?

In Python, memory is managed using a technique called automatic memory management or garbage collection. Python's built-in garbage collector automatically deallocates memory that is no longer being used by the program. Python maintains a private heap where all objects and data structures are stored. Each object in Python has a reference count, which keeps track of the number of references to the object. When an object's reference count reaches zero, it is marked for garbage collection, and the memory it was using is deallocated. Python's garbage collector uses a technique called "reference counting with cycle detection". In addition to the reference count, Python also tracks objects that have circular references, which can cause memory leaks if not properly handled. When circular references are detected, Python's garbage collector uses a separate algorithm to break the reference cycles and deallocate the memory. In addition to garbage collection, Python also uses a technique called "memory pooling" to optimize memory allocation and deallocation. This involves pre-allocating a pool of memory blocks for commonly used object types, such as integers and small strings. When an object of that type is created, Python can quickly allocate memory from the pre-allocated pool, rather than having to allocate new memory each time. Overall, Python's automatic memory management makes it easier for developers to write code without worrying about memory allocation and deallocation. However, it is important to be aware of memory usage in Python, as inefficient use of memory can lead to performance issues and slowdowns.

What is pickling and unpickling?

In Python, pickling and unpickling are methods of serializing and deserializing Python objects. Pickling is the process of converting a Python object hierarchy into a byte stream, which can then be stored in a file or transmitted over a network. Unpickling is the reverse process of restoring the object hierarchy from the byte stream. The pickle module in Python provides functions for pickling and unpickling Python objects. The dump function can be used to pickle an object to a file, and the load function can be used to unpickle an object from a file. Similarly, the dumps function can be used to pickle an object to a byte string, and the loads function can be used to unpickle an object from a byte string.

Pickling and unpickling can be useful for a variety of purposes, such as:

  1. Storing and retrieving data structures from a file or database
  2. Passing data between different processes or machines
  3. Caching frequently used objects for faster access

However, it is important to note that not all Python objects can be pickled, and care must be taken to ensure that pickled objects are secure and not subject to malicious attacks.

Is indentation required in python?

Yes, indentation is required in Python. In fact, indentation is a fundamental part of Python's syntax and is used to define the scope of blocks of code, such as functions, loops, and conditional statements. In most other programming languages, code blocks are defined using curly braces or other symbols. In Python, however, code blocks are defined by the level of indentation. This means that all code within a block must be indented to the same level, and the end of the block is indicated by returning to the previous level of indentation.

Does Python have OOps concepts?

Yes, Python is an object-oriented programming (OOP) language, and it fully supports all the major OOP concepts, including encapsulation, inheritance, and polymorphism.

In Python, everything is an object, and you can define classes to create new types of objects with their own properties and methods. Classes can inherit properties and methods from other classes, and you can use polymorphism to define different behaviors for objects of the same class or of different classes. Python also supports encapsulation, which allows you to hide the implementation details of a class from other parts of the program. You can use access modifiers to control the visibility of properties and methods, so that only certain parts of the program can access them.

What is monkey patching in Python?

In Python, monkey patching is the process of modifying a module or object at runtime, typically by replacing one or more of its methods or attributes with different implementations. Monkey patching is a powerful technique that can be used to modify the behavior of third-party libraries or to add new features to existing code.

Monkey patching is typically done by importing the module or object to be modified, then redefining one or more of its methods or attributes. For example, you might monkey patch a method of a class to add new functionality or to fix a bug:

# Original method class MyClass: def my_method(self): print("Hello, world!")
# Monkey-patched method def new_method(self): print("Goodbye, world!") MyClass.my_method = new_method

In the above example, the my_method method of the MyClass class has been monkey patched to print "Goodbye, world!" instead of "Hello, world!".

While monkey patching can be a powerful technique, it can also be risky, since it can potentially introduce bugs or unexpected behavior if not done carefully. Therefore, it should be used with caution and only in situations where it is necessary or justified.

top Python Interview questions

Does python make use of access specifiers?

Python does not have access specifiers in the same way that some other object-oriented programming languages do. In languages like Java, for example, you can use access specifiers like public, private, and protected to control the visibility of class members (methods and properties). In Python, all attributes and methods are technically public, but there are conventions that are commonly used to indicate whether an attribute or method is intended to be used internally or externally. The convention is to prefix the name of an attribute or method with a single underscore (_) to indicate that it is intended to be used only within the module where it is defined. A double underscore (__) prefix is used to indicate that a method or attribute should not be overridden in subclasses. Although these naming conventions are not strictly enforced by the Python language itself, they are widely recognized and followed by Python developers to help ensure code clarity and maintainability.

What are Python decorators?

Python decorators are a way to modify or extend the behavior of a function or method without changing its source code. A decorator is a special type of function that takes another function as its argument and returns a new function that adds some kind of behavior to the original function.

The syntax for applying a decorator to a function is to use the @decorator_name syntax before the function definition.

What are negative indices?

In Python, negative indices are a way to access elements of a sequence (such as a list, tuple, or string) from the end of the sequence, rather than from the beginning. The index -1 refers to the last element in the sequence, -2 refers to the second-to-last element, and so on.

For example, consider the following list:

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

To access the first element of the list, you would use the index 0:

>>> my_list[0] 'a'

To access the last element of the list, you can use the index -1:

>>> my_list[-1] 'e'

Similarly, to access the second-to-last element, you would use the index -2:

>>> my_list[-2] 'd'

Negative indices can be useful when working with sequences where you don't know the length in advance, or when you want to access elements relative to the end of the sequence.

What is the purpose of ** operator?

In Python, the double-asterisk (**) operator is used to raise a number to a power. Specifically, it is used for exponentiation, which means raising a number to a certain power. For example, the expression 2 ** 3 evaluates to 8, because it raises 2 to the power of 3 (which is 2 multiplied by itself 3 times).

The ** operator can also be used with variables and more complex expressions. For example:

x = 4 y = 3 z = x ** y print(z) # Output: 64
In the above example, the variable x is raised to the power of y using the ** operator, and the result is assigned to the variable z. When the code is run, the value of z is 64.

What is the purpose of // operator?

In Python, the double-slash (//) operator is used for floor division, which means dividing two numbers and rounding down to the nearest whole number. This is in contrast to regular division, which can result in a fractional answer.

For example, if you perform regular division on 7 and 2, you get 3.5:

>>> 7 / 2 3.5

However, if you perform floor division on 7 and 2, you get 3 (because 3 is the nearest whole number less than 3.5):

>>> 7 // 2 3

Floor division is useful in situations where you need to divide two numbers and get an integer result. For example, if you are working with measurements or quantities that cannot be fractional, floor division can be used to ensure that the result is a whole number.

Note that if both operands are integers, the result of the division will be an integer. However, if either operand is a float, the result will be a float.

How will you convert an object to a string in python?

In Python, you can convert an object to a string using the str() function. This function takes an object as an argument and returns a string representation of the object.

Here's an example:

num = 42 num_string = str(num) print(num_string) # Output: "42"

In this example, the str() function is used to convert the integer variable num to a string. The resulting string, "42", is then assigned to the variable num_string.

Note that not all objects can be converted to strings using the str() function. If an object does not have a defined string representation, the str() function will raise a TypeError exception. In such cases, you may need to define a custom string representation for the object using the __str__() method.

What are membership operators?

Membership operators in Python are used to test if a value is a member of a sequence, such as a string, list, or tuple. The two membership operators are in and not in.

Here's an example:

my_list = [1, 2, 3, 4, 5] if 3 in my_list: print("3 is in the list") else: print("3 is not in the list")

In the above example, the in operator is used to test if the value 3 is a member of the list my_list. Since 3 is in the list, the output of the code is "3 is in the list".

The not in operator is used to test if a value is not a member of a sequence. Here's an example:

my_string = "Hello, world!" if "z" not in my_string: print("z is not in the string") else: print("z is in the string")

In this example, the not in operator is used to test if the letter "z" is not in the string my_string. Since "z" is not in the string, the output of the code is "z is not in the string".

What is zip() function in Python?

In Python, zip() is a built-in function that takes one or more iterables and aggregates their elements into tuples of corresponding elements. It returns a zip object, which is an iterator of tuples, where the i-th tuple contains the i-th element from each of the input iterables.

Here's an example:

list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] zipped = zip(list1, list2) print(list(zipped)) # Output: [(1, 'a'), (2, 'b'), (3, 'c')]
In the above example, the zip() function is used to aggregate the elements of two lists, list1 and list2, into tuples. The resulting tuples are then converted to a list using the list() function and printed to the console. If the input iterables are of different lengths, zip() will stop aggregating elements as soon as the shortest input iterable is exhausted. Any remaining elements from the longer iterables will be ignored. Note that in Python 3.x, zip() returns an iterator, whereas in Python 2.x, it returns a list. If you need a list in Python 3.x, you can convert the zip object to a list using the list() function, as shown in the example above.

How do you find the type and identification number of an object in Python?

In Python, you can use the built-in type() and id() functions to find the type and identification number of an object, respectively.

Here's an example:

x = 42 print(type(x)) # Output: <class 'int'> print(id(x)) # Output: 140721874310336

In this example, the type() function is used to find the type of the integer object x, which is int. The id() function is used to find the identification number of x.

What is the output of print(txt * 2) if txt = 'Python Tutorial!'?

If txt = 'Python Tutorial!', the output of print(txt * 2) would be:

Python Tutorial!Python Tutorial!

The * operator is used to repeat a string a certain number of times. In this case, txt * 2 concatenates txt with itself, resulting in two copies of the original string.

Difference between Deep copy and Shallow copy?

In Python, there are two ways to copy an object: shallow copy and deep copy.

A shallow copy creates a new object but does not create new objects for any nested objects. Instead, it creates references to the original nested objects. Therefore, changes made to the original nested objects will be reflected in the copied object as well. A deep copy creates a new object and also creates new objects for any nested objects. Therefore, changes made to the original nested objects will not be reflected in the copied object.

How to determine the type of an object?

In Python, you can use the type() function to determine the type of an object.

Difference between del[], remove() and pop() on list?

In Python, there are several ways to remove items from a list:

  1. del: removes an item from a list by its index
  2. remove(): removes an item from a list by its value
  3. pop(): removes an item from a list by its index and returns the removed item

Write a generator expression to get the numbers that are divisible by 3?

You can use a generator expression with a conditional statement to generate the numbers that are divisible by 3. Here's an example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Generator expression to get the numbers that are divisible by 3 divisible_by_3 = (num for num in numbers if num % 3 == 0) # Iterate over the generator expression and print the results for num in divisible_by_3: print(num)

This will output:

3 6 9

How many kinds of sequences are supported by Python? What are they?

Python supports several kinds of sequences. The main types are:

  1. Lists: Lists are the most commonly used sequence in Python. They are mutable and can contain any type of object.
  2. Tuples: Tuples are similar to lists, but they are immutable. Once a tuple is created, its contents cannot be changed.
  3. Strings: Strings are sequences of characters. They are immutable, which means that you cannot modify the contents of a string once it has been created.
  4. Byte arrays: Byte arrays are like byte strings, but they are mutable. They are often used in low-level programming tasks that involve manipulating binary data.
  5. Range objects: Range objects are used to generate a sequence of numbers. They are often used in loops and other control flow statements.
  6. Bytes and byte strings: These are sequences of bytes. Bytes are immutable, while byte strings are mutable.

There are other sequence types in Python as well, but these are the most commonly used.

How do you call an external command from Python script?

You can call an external command from a Python script by using the subprocess module, which provides a way to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. To call an external command using the subprocess module, you can use the subprocess.run() function, which takes the command and its arguments as a list of strings. For example, to call the ls command in a Unix-based system, you can use the following code:
import subprocess result = subprocess.run(["ls", "-l"])
This will run the ls -l command and store the result in the result variable. You can then access the output of the command using the result.stdout attribute.

What is GIL in Python

The Global Interpreter Lock (GIL) is a mechanism used in the Python programming language to synchronize the execution of threads. The GIL is a mutex (a mutual exclusion object) that allows only one thread to execute Python bytecode at a time. This means that even on a multi-core processor, only one thread can execute Python code at any given time.

Last Updated : 29 Mar 2023