A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-interview-questions/ below:

Python Interview Questions and Answers

Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Python Interview Questions. We have prepared a list of the Top 50 Python Interview Questions along with their answers to ace interviews.

Python Interview Questions for Freshers 1. Is Python a compiled language or an interpreted language?

Please remember one thing, whether a language is compiled or interpreted or both is not defined in the language standard. In other words, it is not a properly of a programming language. Different Python distributions (or implementations) choose to do different things (compile or interpret or both). However the most common implementations like CPython do both compile and interpret, but in different stages of its execution process.

Some implementations, like PyPy, use Just-In-Time (JIT) compilation, where Python code is compiled into machine code at runtime for faster execution, blurring the lines between interpretation and compilation.

2. How can you concatenate two lists in Python?

We can concatenate two lists in Python using the +operator or the extend() method.

1. Using the + operator:

This creates a new list by joining two lists together.

Python
a = [1, 2, 3]
b = [4, 5, 6]
res = a + b
print(res) 

Output
[1, 2, 3, 4, 5, 6]

2. Using the extend() method:

This adds all the elements of the second list to the first list in-place.

Python
a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)
print(a) 

Output
[1, 2, 3, 4, 5, 6]
3. Difference between for loop and while loop in Python Python
for i in range(5):
    print(i)

c = 0
while c < 5:
    print(c)
    c += 1

Output
0
1
2
3
4
0
1
2
3
4
4. How do you floor a number in Python?

To floor a number in Python, you can use the math.floor() function, which returns the largest integer less than or equal to the given number.

Python
import math

n = 3.7
F_num = math.floor(n)

print(F_num) 
5. What is the difference between / and // in Python?

/ represents precise division (result is a floating point number) whereas // represents floor division (result is an integer). For Example:

Python 6. Is Indentation Required in Python?

Yes, indentation is required in Python. A Python interpreter can be informed that a group of statements belongs to a specific block of code by using Python indentation. Indentations make the code easy to read for developers in all programming languages but in Python, it is very important to indent the code in a specific order.

Python Indentation 7. Can we Pass a function as an argument in Python?

Yes, Several arguments can be passed to a function, including objects, variables (of the same or distinct data types) and functions. Functions can be passed as parameters to other functions because they are objects. Higher-order functions are functions that can take other functions as arguments.

Python
def add(x, y):
    return x + y

def apply_func(func, a, b):
    return func(a, b)

print(apply_func(add, 3, 5))

The add function is passed as an argument to apply_func, which applies it to 3 and 5.

8. What is a dynamically typed language?

Example:

Python
x = 10       # x is an integer
x = "Hello"  # Now x is a string

Here, the type of x changes at runtime based on the assigned value hence it shows dynamic nature of Python.

9. What is pass in Python? Python
def fun():
    pass  # Placeholder, no functionality yet

# Call the function
fun()

Here, fun() does nothing, but the code stays syntactically correct.

10. How are arguments passed by value or by reference in Python?

You can check the difference between pass-by-value and pass-by-reference in the example below:

Python
def call_by_val(x):
    x = x * 2
    return x


def call_by_ref(b):
    b.append("D")
    return b


a = ["E"]
num = 6

# Call functions
updated_num = call_by_val(num)
updated_list = call_by_ref(a)

# Print after function calls
print("Updated value after call_by_val:", updated_num)
print("Updated list after call_by_ref:", updated_list)

Output
Updated value after call_by_val: 12
Updated list after call_by_ref: ['E', 'D']
11. What is a lambda function?

A lambda function is an anonymous function. This function can have any number of parameters but, can have just one statement.

In the example, we defined a lambda function(upper) to convert a string to its upper case using upper().

Python
s1 = 'GeeksforGeeks'

s2 = lambda func: func.upper()
print(s2(s1))
12. What is List Comprehension? Give an Example.

List comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques.

For example, if we have a list of integers and want to create a new list containing the square of each element, we can easily achieve this using list comprehension.

Python
a = [2,3,4,5]
res = [val ** 2 for val in a]
print(res)
13. What are *args and **kwargs? Python
def fun(*argv):
    for arg in argv:
        print(arg)

fun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

Output
Hello
Welcome
to
GeeksforGeeks
Python
def fun(**kwargs):
    for k, val in kwargs.items():
        print("%s == %s" % (k, val))


# Driver code
fun(s1='Geeks', s2='for', s3='Geeks')

Output
s1 == Geeks
s2 == for
s3 == Geeks
14. What is a break, continue and pass in Python?  15. What is the difference between a Set and Dictionary?

my_set = {1, 2, 3}

my_dict = {"a": 1, "b": 2, "c": 3}

16. What are Built-in data types in Python?

The following are the standard or built-in data types in Python:

17. What is the difference between a Mutable datatype and an Immutable data type? 18. What is a Variable Scope in Python?

The location where we can find a variable and also access it if required is called the scope of a variable.

19. How is a dictionary different from a list?

A list is an ordered collection of items accessed by their index, while a dictionary is an unordered collection of key-value pairs accessed using unique keys. Lists are ideal for sequential data, whereas dictionaries are better for associative data. For example, a list can store [10, 20, 30], whereas a dictionary can store {"a": 10, "b": 20, "c": 30}.

20. What is docstring in Python?

Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes and methods.

21. How is Exceptional handling done in Python?

There are 3 main keywords i.e. try, except and finally which are used to catch exceptions:

Example: Trying to divide a number by zero will cause an exception.

Python
n = 10
try:
    res = n / 0  # This will raise a ZeroDivisionError
    
except ZeroDivisionError:
    print("Can't be divided by zero!")

Output
Can't be divided by zero!

Explanation: In this example, dividing number by 0 raises a ZeroDivisionError. The try block contains the code that might cause an exception and the except block handles the exception, printing an error message instead of stopping the program.

22. What is the difference between Python Arrays and Lists?

Example:

Python
from array import array
arr = array('i', [1, 2, 3, 4])  # Array of integers

Example:

Python
a = [1, 'hello', 3.14, [1, 2, 3]]

read more about Difference between List and Array in Python

23. What are Modules and Packages in Python?

A module is a single file that contains Python code (functions, variables, classes) which can be reused in other programs. You can think of it as a code library. For example: math is a built-in module that provides math functions like sqrt(), pi, etc.

Python
import math
print(math.sqrt(16))  

package is a collection of related modules stored in a directory. It helps in organizing and grouping modules together for easier management. For example: The numpy package contains multiple modules for numerical operations.

To create a package, the directory must contain a special file named __init__.py.

24. What is the difference between xrange and range functions?

range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. 

25. What is Dictionary Comprehension? Give an Example

Dictionary Comprehension is a syntax construction to ease the creation of a dictionary based on the existing iterable.

Python
keys = ['a','b','c','d','e']
values = [1,2,3,4,5]  

# this line shows dict comprehension here  
d = { k:v for (k,v) in zip(keys, values)}  

# We can use below too
# d = dict(zip(keys, values))  

print (d)

Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
26. Is Tuple Comprehension possible in Python? If yes, how and if not why?

Tuple comprehensions are not directly supported, Python's existing features like generator expressions and the tuple() function provide flexible alternatives for creating tuples from iterable data.

(i for i in (1, 2, 3))

Tuple comprehension is not possible in Python because it will end up in a generator, not a tuple comprehension.

27. Differentiate between List and Tuple?

Let’s analyze the differences between List and Tuple:

List

Tuple

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

Below is the tabular Difference between the Shallow Copy and Deep Copy:

Shallow Copy Deep Copy Shallow Copy stores the references of objects to the original memory address.    Deep copy stores copies of the object’s value. Shallow Copy reflects changes made to the new/copied object in the original object. Deep copy doesn’t reflect changes made to the new/copied object in the original object. Shallow Copy stores the copy of the original object and points the references to the objects. Deep copy stores the copy of the original object and recursively copies the objects as well. A shallow copy is faster. Deep copy is comparatively slower. 29. Which sorting technique is used by sort() and sorted() functions of python?

Python uses the Tim Sort algorithm for sorting. It’s a stable sorting whose worst case is O(N log N). It’s a hybrid sorting algorithm, derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data.

30. What are Decorators?

Decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality.

Decorators are often used in scenarios such as logging, authentication and memorization, allowing us to add additional functionality to existing functions or methods in a clean, reusable way.

31. How do you debug a Python program?

1. Using pdb (Python Debugger):

pdb is a built-in module that allows you to set breakpoints and step through the code line by line. You can start the debugger by adding import pdb; pdb.set_trace() in your code where you want to begin debugging.

Python
import pdb
x = 5
pdb.set_trace()  # Debugger starts here
print(x)

Output

> /home/repl/02c07243-5df9-4fb0-a2cd-54fe6d597c80/main.py(4)<module>()
-> print(x)
(Pdb)

2. Using logging Module:

For more advanced debugging, the logging module provides a flexible way to log messages with different severity levels (INFO, DEBUG, WARNING, ERROR, CRITICAL).

Python
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("This is a debug message")

Output

DEBUG:root:This is a debug message

32. What are Iterators in Python?

In Python, iterators are used to iterate a group of elements, containers like a list. Iterators are collections of items and they can be a list, tuples, or a dictionary. Python iterator implements __itr__ and the next() method to iterate the stored elements. We generally use loops to iterate over the collections (list, tuple) in Python.

33. What are Generators in Python?

In Python, the generator is a way that specifies how to implement iterators. It is a normal function except that it yields expression in the function. It does not implement __itr__ and __next__ method and reduces other overheads as well.

If a function contains at least a yield statement, it becomes a generator. The yield keyword pauses the current execution by saving its states and then resumes from the same when required.

34. Does Python supports multiple Inheritance?

When a class is derived from more than one base class it is called multiple Inheritance. The derived class inherits all the features of the base case.

Multiple Inheritance

Python does support multiple inheritances, unlike Java.

35. What is Polymorphism in Python?

Polymorphism means the ability to take multiple forms. Polymorphism allows different classes to be treated as if they are instances of the same class through a common interface. This means that a method in a parent class can be overridden by a method with the same name in a child class, but the child class can provide its own specific implementation. This allows the same method to operate differently depending on the object that invokes it. Polymorphism is about overriding, not overloading; it enables methods to operate on objects of different classes, which can have their own attributes and methods, providing flexibility and reusability in the code.

36. Define encapsulation in Python?

Encapsulation is the process of hiding the internal state of an object and requiring all interactions to be performed through an object’s methods. This approach:

Python achieves encapsulation through publicprotected and private attributes.

Encapsulation in Python 37. How do you do data abstraction in Python?

Data Abstraction is providing only the required details and hides the implementation from the world. The focus is on exposing only the essential features and hiding the complex implementation behind an interface. It can be achieved in Python by using interfaces and abstract classes.

38. How is memory management done in Python?

Python uses its private heap space to manage the memory. Basically, all the objects and data structures are stored in the private heap space. Even the programmer can not access this private space as the interpreter takes care of this space. Python also has an inbuilt garbage collector, which recycles all the unused memory and frees the memory and makes it available to the heap space.

39. How to delete a file using Python?

We can delete a file using Python by following approaches:

  1. Python Delete File using os. remove
  2. Delete file in Python using the send2trash module
  3. Python Delete File using os.rmdir
40. What is slicing in Python?

Python Slicing is a string operation for extracting a part of the string, or some part of a list. With this operator, one can specify where to start the slicing, where to end and specify the step. List slicing returns a new list from the existing list.

Syntax:

substring = s[start : end : step]

41. What is a namespace in Python?

A namespace in Python refers to a container where names (variables, functions, objects) are mapped to objects. In simple terms, a namespace is a space where names are defined and stored and it helps avoid naming conflicts by ensuring that names are unique within a given scope.

Types of namespaces

Types of Namespaces:

  1. Built-in Namespace: Contains all the built-in functions and exceptions, like print(), int(), etc. These are available in every Python program.
  2. Global Namespace: Contains names from all the objects, functions and variables in the program at the top level.
  3. Local Namespace: Refers to names inside a function or method. Each function call creates a new local namespace.
Python Interview Advanced Python Interview Questions & Answers  42. What is PIP?

PIP is an acronym for Python Installer Package which provides a seamless interface to install various Python modules. It is a command-line tool that can search for packages over the internet and install them without any user interaction.

43. What is a zip function?

Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, converts it into an iterator and aggregates the elements based on iterables passed. It returns an iterator of tuples.

Syntax:
zip(*iterables) 

44. What are Pickling and Unpickling? 45. What is the difference between @classmethod, @staticmethod and instance methods in Python?

1. Instance Method operates on an instance of the class and has access to instance attributes and takes self as the first parameter. Example:

def method(self):

2. Class Method directly operates on the class itself and not on instance, it takes cls as the first parameter and defined with @classmethod.

Example: @classmethod def method(cls):

3. Static Method does not operate on an instance or the class and takes no self or cls as an argument and is defined with @staticmethod.

Example: @staticmethod def method(): align it and dont bolod anything and not bullet points

46. What is __init__() in Python and how does self play a role in it? Python
class MyClass:
    def __init__(self, value):
        self.value = value  # Initialize object attribute

    def display(self):
        print(f"Value: {self.value}")

obj = MyClass(10)
obj.display() 
47. Write a code to display the current time? Python
import time

currenttime= time.localtime(time.time())
print ("Current time is", currenttime)

Output
Current time is time.struct_time(tm_year=2025, tm_mon=6, tm_mday=10, tm_hour=11, tm_min=56, tm_sec=57, tm_wday=1, tm_yday=161, tm_isdst=0)
48. What are Access Specifiers in Python?

Python uses the ‘_’ symbol to determine the access control for a specific data member or a member function of a class. A Class in Python has three types of Python access modifiers:

49. What are unit tests in Python?

Unit Testing is the first level of software testing where the smallest testable parts of the software are tested. This is used to validate that each unit of the software performs as designed. The unit test framework is Python’s xUnit style framework. The White Box Testing method is used for Unit testing.

50. Python Global Interpreter Lock (GIL)?

Python Global Interpreter Lock (GIL) is a type of process lock that is used by Python whenever it deals with processes. Generally, Python only uses only one thread to execute the set of written statements. The performance of the single-threaded process and the multi-threaded process will be the same in Python and this is because of GIL in Python. We can not achieve multithreading in Python because we have a global interpreter lock that restricts the threads and works as a single thread.

51. What are Function Annotations in Python? 52. What are Exception Groups in Python?

The latest feature of Python 3.11, Exception Groups. The ExceptionGroup can be handled using a new except* syntax. The * symbol indicates that multiple exceptions can be handled by each except* clause.

ExceptionGroup is a collection/group of different kinds of Exception. Without creating Multiple Exceptions we can group together different Exceptions which we can later fetch one by one whenever necessary, the order in which the Exceptions are stored in the Exception Group doesn’t matter while calling them.

try:
raise ExceptionGroup('Example ExceptionGroup', (
TypeError('Example TypeError'),
ValueError('Example ValueError'),
KeyError('Example KeyError'),
AttributeError('Example AttributeError')
))
except* TypeError:
...
except* ValueError as e:
...
except* (KeyError, AttributeError) as e:
...

53. What is Python Switch Statement?

From version 3.10 upward, Python has implemented a switch case feature called “structural pattern matching”. You can implement this feature with the match and case keywords. Note that the underscore symbol is what you use to define a default case for the switch statement in Python.

Note: Before Python 3.10 Python doesn't support match Statements.

Python
match term:
   case pattern-1:
   action-1
   case pattern-2:
   action-2
   case pattern-3:
   action-3
   case _:
   action-default
54. What is Walrus Operator?

Note: Python versions before 3.8 doesn't support Walrus Operator.

Python
numbers = [1, 2, 3, 4, 5]

while (n := len(numbers)) > 0:
    print(numbers.pop())


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4