0% found this document useful (0 votes)
4 views12 pages

Python Interview Questions

Uploaded by

Kumar Mukand
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views12 pages

Python Interview Questions

Uploaded by

Kumar Mukand
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

1. Is Python a compiled language or an interpreted language?

 Python is primarily considered an interpreted language, means


code is run line by line there is no compilation step.

2. What is the difference between interpreted and compiled languages?


 Interpreted languages execute code directly from the source,
while compiled languages translate code into machine language
before execution.

3. What are the advantages and disadvantages of interpreted and compiled


languages?
 Interpreted languages have platform independence, faster development, dynamic
typing, ease of debugging.
 Complied languages have better performance, static typing, executable efficiency,
security.

4. What does the ‘#’ symbol do in Python?


 In Python, the # symbol is used to indicate a comment. Comments are lines in the
code that are ignored by the Python interpreter and are intended for human readers
to understand the code. They are useful for adding explanations, notes, or
annotations to the code.

5. What is the difference between a Mutable datatype and an Immutable data type?
 Mutable data types allow their values to be changed after creation.
 Examples of mutable data types in Python include lists, dictionaries, and sets.

 Immutable data types do not allow their values to be changed after they are
created.
 Examples of immutable data types in Python include strings, tuples, and
frozensets.

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


 In python whether arguments are passed by value or by reference depend on the
data type, which is being passed, so immutable objects, such as integers, floats,
strings, and tuples, cannot be modified after creation, so changes made to this
reference within the function do not affect the original object outside the function.
While mutable objects, such as lists, dictionaries, and sets, can be modified after
creation, so any modifications made to this reference within the function will
affect the original object outside the function.

7. What is the difference between sets, tuples, dictionaries, frozensets, and lists in
Python?
 Sets, tuples, dictionaries, frozensets, and lists are all fundamental data
structures in Python, each with unique properties and suitable applications.
Sets are unordered collections of unique elements, often used for
membership testing and mathematical operations like union and
intersection. For example, my_set = {1, 2, 3} creates a set with elements 1,
2, and 3. Tuples, on the other hand, are ordered collections of elements
that cannot be changed after creation, making them ideal for representing
fixed sequences of values like coordinates or database records. An
example would be my_tuple = (1, 2, 3). Dictionaries are key-value pairs,
allowing fast lookups and storage of associated data. They're commonly
used for data indexing and storing configuration settings. For instance,
my_dict = {"name": "Alice", "age": 30} creates a dictionary with keys
"name" and "age". Frozensets are immutable versions of sets, useful in
situations where you need a set as a key in another dictionary or as an
element in another set. An example is my_frozenset = frozenset ([1, 2, 3]).
Lastly, lists are ordered collections of elements that can be changed after
creation, making them versatile for dynamic data storage and
manipulation. They're often used for tasks like maintaining queues or
implementing algorithms that require mutable sequences. For example,
my_list = [1, 2, 3] creates a list with elements 1, 2, and 3. By
understanding the characteristics and use cases of these data structures,
Python developers can choose the most appropriate one for their specific
programming needs.

8. What is List Comprehension? Give an Example.


 List comprehension is a concise and elegant way of creating lists in Python. It
allows you to generate a new list by applying an expression to each item in an
iterable and optionally filtering the items based on a condition, all in a single line
of code. For example, to create a list of squares of numbers from 1 to 5, you can
use list comprehension like this: squares = [x * x for x in range(1, 6)]. This one-
liner replaces the traditional approach of using loops and appending to a list,
making the code more readable and compact. List comprehension is a powerful
feature that simplifies list creation tasks and is widely used in Python
programming for its simplicity and efficiency.

9. What is a lambda function?


 A lambda function in Python is a concise way of creating anonymous functions,
defined using the lambda keyword. Unlike regular functions defined with def,
lambda functions don't have a name and are limited to a single expression. They
are often used for short, throwaway functions that are needed only temporarily or
within a limited scope. For example, you can use a lambda function to define a
simple operation, such as adding two numbers: addition = lambda x, y: x + y. This
defines a lambda function that takes two arguments x and y and returns their sum.
You can then use this function like any other function, such as addition(3, 5),
which would return 8. Lambda functions are commonly used in conjunction with
functions like map (), filter(), and sorted() to provide quick and concise ways of
applying operations or filtering elements within iterables.

10. What is a pass in Python?


 In Python, pass is a statement used as a placeholder to indicate that no action
should be taken. It serves as a way to satisfy syntactic requirements without
executing any code. For example, in an empty function definition where you plan
to implement functionality later, you can use pass to avoid syntax errors:
11. What is the difference between / and // in Python?
 / and // are both division operators with distinct behaviors. The single slash /
represents "true division" and always returns a floating-point result, even when
dividing two integers. For instance, 7 / 3 would yield 2.3333333333333335. On
the other hand, the double slash // denotes "floor division" and returns the quotient
rounded down to the nearest integer. For example, 7 // 3 would result in 2. This
operator discards any fractional part of the division. Therefore, while / always
produces a floating-point output, // gives an integer output, making it particularly
useful when you need integer division.

12. How is Exceptional handling done in Python?


 Exception handling in Python allows you to manage errors and unexpected
situations that may occur during the execution of your code. The try, except, else,
and finally blocks are used for this purpose. Inside a try block, you place the code
that could potentially raise an exception. If an exception occurs within the try
block, Python looks for a matching except block to handle it. You can specify the
type of exception to catch, or use a generic except block to catch any exception.
 try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero!"
 Optionally, you can include an else block after the except block. Code within the
else block will execute only if no exception occurs in the try block. For example:
 try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
 else:
print("Division successful!")
 Furthermore, a finally block can be added after the except and else blocks. Code
within the finally block will execute regardless of whether an exception occurred
or not. This block is commonly used for cleanup actions, such as closing files or
releasing resources:
 try:
result = 10 / 2
 except ZeroDivisionError:
print("Cannot divide by zero!")
 else:
print("Division successful!")
 finally:
print("Execution complete!")

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


 Yes, in Python, you can pass functions as arguments to other functions. This
feature enables you to create more flexible and reusable code.
 def add(x, y):
return x + y
 def subtract(x, y):
return x - y

 def apply_operation(operation, x, y):


return operation(x, y)

result1 = apply_operation(add, 5, 3)
 print(result1) # Output: 8

 result2 = apply_operation(subtract, 10, 4)


print(result2) # Output: 6

14. What are *args and *kwargs?


 In Python, *args and **kwargs serve as special syntax in function definitions to
handle varying numbers of arguments.
 *args permits a function to receive an arbitrary number of positional arguments,
which are aggregated into a tuple. This is particularly advantageous when you
need to pass an unknown number of arguments to a function without explicitly
specifying each one.

 def my_function(*args):
 for arg in args:
 print(arg)

 my_function(1, 2, 3) # Output: 1 2 3

 On the other hand, **kwargs allows a function to accept an arbitrary number of


keyword arguments, which are accumulated into a dictionary. This is beneficial
when passing named arguments without prior knowledge of their names. An
example implementation would resemble:

 def my_function(**kwargs):
 for key, value in kwargs.items():
 print(f"{key}: {value}")

 my_function(name="Alice", age=30, city="New York")


 # Output: name: Alice, age: 30, city: New York

 By utilizing *args and **kwargs, you enhance the flexibility and adaptability of
your functions, permitting them to accept varying argument combinations
seamlessly.

15. Is Indentation Required in Python?


 Yes indentation is very important in python as there are no brackets.
16. What is Scope in Python?
 In Python, scope refers to the region of a program where a particular variable is
accessible. It determines the visibility and lifetime of variables within the
program. For instance, variables defined within a function have a local scope,
meaning they are only accessible within that function. Conversely, variables
defined outside of any function or in the global scope are accessible from
anywhere within the program.
17. What is docstring in Python?
 In Python, a docstring is a string literal that occurs as the first statement in a
module, function, class, or method definition. Its purpose is to provide
documentation about the purpose, usage, and behavior of the object it precedes.
Docstrings are enclosed in triple quotes (either single or double) and are typically
written in a human-readable format, such as plain text or reStructuredText (reST).
 def greet(name):
 """
 This function greets the user with the given name.

 Parameters:
 name (str): The name of the user to greet.

 Returns:
 str: A greeting message.
 """
 return f"Hello, {name}!"

18. is python a dynamically typed language?


 Yes it is a dynamically typed language is a programming language where the type
of a variable is determined at runtime rather than at compile time. In dynamically
typed languages, variables are not bound to a specific data type during declaration,
and their type can change as the program runs.

19. What is a break, continue, and pass in Python?


 break is a keyword used to exit from a loop prematurely. When encountered
within a loop (such as for or while), it immediately terminates the loop's
execution, regardless of the loop's condition.
 continue is a keyword used to skip the remaining code within a loop's iteration
and move to the next iteration. When encountered within a loop, it skips the
current iteration's remaining code and proceeds to the next iteration.
 pass is a keyword used as a placeholder when syntactically required but no action
is needed. It does nothing when executed and is often used to fill in empty code
blocks, function definitions, or conditional statements where code is expected but
not yet implemented.

20. What is the difference between tuple and frozen sets?


 Yes, both frozen sets and tuples can be used for similar things like
collecting data. However, frozen sets are mainly for collecting unique
items that won't change, while tuples are for keeping things in a certain
order that won't change. One major difference is that tuple can duplicates
but fozen set don’t be havin duplicates.

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


 range(): Returns a list containing the specified range of integers
 xrange(): Returns an xrange object, which is an iterable representing the
sequence of integers. It does not generate the entire list of numbers at once
but instead generates them one at a time as needed, which can save
memory for large ranges.

22. What is Dictionary Comprehension?


 Dictionary comprehension is a concise way to create dictionaries in Python
using a single line of code. It allows you to generate dictionaries by specifying
key-value pairs and optional conditions, similar to list comprehensions but for
dictionaries.

 # Creating a dictionary of squares of numbers from 1 to 5


 squares_dict = {num: num ** 2 for num in range(1, 6)}
 print(squares_dict) {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

23. Is Tuple Comprehension? If yes, how, and if not why?


 No there is no tuple comphension in python.

24. Differentiate between List and Tuple?

 Lists (list): Lists are mutable, meaning their elements can be changed after
creation. You can add, remove, or modify elements in a list.
 Tuples (tuple): Tuples are immutable, meaning once created, their elements
cannot be changed. You cannot add, remove, or modify elements in a tuple after it
has been created.

25. What is the difference between a shallow copy and a deep copy?
 Shallow copies share references to nested objects and reflect changes made to
them, deep copies create independent copies of both the top-level structure and
nested objects, ensuring changes made to the copy do not affect the original
object.

26. Which sorting technique is used by sort() and sorted() functions of python?
 The sort() method and the sorted() function in Python use the Timsort algorithm
for sorting.
 Timsort is a hybrid sorting algorithm derived from merge sort and insertion sort. It
was designed to perform well on many kinds of real-world data and is the default
sorting algorithm in Python because of its stability, efficiency, and adaptability to
various input types.

27. What are Decorators?


 Decorators in Python are functions that modify the behavior of other functions or
methods. They allow you to add functionality to existing functions without
modifying their code directly. Decorators are commonly used for tasks such as
logging, authentication, caching, or adding functionality to multiple functions in a
consistent way. In Python, decorators are implemented using the
@decorator_name syntax, where decorator_name is the name of the decorator
function. You place this syntax on the line above the function definition you want
to decorate. When you call the decorated function, the decorator function is
invoked first, and its behavior is applied to the original function.
28. How do you debug a Python program?
 Print Statements: Insert print statements to display variable values and program
flow.
 Debugger: Use built-in (pdb) or third-party debuggers like ipdb.
 IDE Features: Utilize debugging tools in IDEs such as PyCharm or Visual Studio
Code.
 Exception Handling: Implement try-except blocks to catch and handle errors.
 Unit Tests: Write and run unit tests to identify bugs early.

29. What are Iterators in Python?


 Iterators are used to iterate over sequences of data, such as lists, tuples, or strings,
in a lazy and memory-efficient manner. They allow you to access elements of a
sequence one at a time without loading the entire sequence into memory at once.
__iter__() and __next__().
30. What are Generators in Python?
 Generators in Python are functions that produce a sequence of values lazily, one at
a time, using the yield keyword. They allow you to iterate over a potentially
infinite sequence without storing the entire sequence in memory at once.

31. Does Python supports multiple Inheritance?


 Yes, Python supports multiple inheritance, which means a class can inherit
attributes and methods from more than one parent class. This allows for the
creation of complex class hierarchies and promotes code reuse.

32. What is Polymorphism in Python?


33. Define encapsulation in Python?
34. How do you do data abstraction in Python?
35. How is memory management done in Python?
 Memory management in Python is handled automatically by the Python memory
manager. It uses reference counting to keep track of the number of references to
objects and garbage collection to reclaim memory from objects with zero
reference counts. Memory pools are used to allocate memory efficiently, and
memory fragmentation is mitigated using optimization techniques. Developers can
use tools like memory_profiler and the gc module for memory profiling and
analysis.

36. What is slicing in Python?


 Slicing in Python is a technique used to extract a portion of a sequence (like lists,
strings, tuples) by specifying a start index, an end index, and an optional step size.

37. What is a namespace in Python?


 A namespace in Python is a system to ensure that all variable names in a program
are unique and can be used without conflict. It organizes the names into scopes
based on the context in which they are defined. For example, a variable defined
inside a function has a different namespace than a variable defined outside the
function.
38. What is PIP?
 PIP is the package installer for Python. It is used to install and manage Python
packages from the Python Package Index (PyPI). PIP comes pre-installed with
Python versions 3.4 and later.

39. What is a zip function?


 The zip() function in Python is used to combine multiple iterables (such as lists,
tuples, or strings) element-wise into tuples. It returns an iterator of tuples where
the i-th tuple contains the i-th element from each of the input iterables.
zipped = zip(list1, list2) # Output: [(1, 'a'), (2, 'b'), (3, 'c')].

40. What are Pickling and Unpickling?


 Pickling is the process of converting a Python object into a byte stream, while
unpickling is the process of reconstructing a Python object from a byte stream.
These processes are used for serializing and deserializing objects, enabling them
to be stored persistently or transmitted over a network. It is is commonly used for
saving and loading complex data structures, caching objects, or passing objects
between processes.

41. What is __init__() in Python?


 In Python, __init__() is a special method known as the constructor. It is
automatically called when a new instance of a class is created. The purpose of
__init__() is to initialize the newly created object by setting up its initial state,
typically by initializing instance variables.

42. Write a code to display the current time?


 To display the current time in Python, you can use the datetime module.

43. What are Access Specifiers in Python?


 Access specifiers in Python, such as public, protected, and private, are not
enforced like in some other programming languages. By convention, attributes
and methods prefixed with a single underscore (_) are considered protected, and
those prefixed with double underscores (__) are considered private, although they
can still be accessed.

44. What are unit tests in Python?


 Unit tests in Python are automated tests written to verify the correctness of
individual units or components of code, typically functions or methods. They are
used to ensure that each unit of the software performs as expected and to detect
any regressions introduced during development or changes.

45. What are Function Annotations in Python?


 Function annotations in Python allow you to attach metadata information to
function parameters and return values. They are defined using colons (:) following
the parameter or return type in function definitions, but they do not affect the
function's behavior.
46. What is Python Switch Statement
 Python does not have a built-in switch statement like some other programming
languages. Instead, the common approach to handling multiple conditions is using
if-elif-else statements.

47. What is faster for lookups in Python: dictionaries or lists?


 Dictionaries are generally faster for lookups in Python compared to lists.
Dictionaries use hash tables for storage, which allows for constant-time average-
case lookups, while lists require iterating through elements linearly, resulting in
linear-time lookups in the worst case.

48. How do you rename columns using Pandas?


 df = df.rename(columns={'A': 'new_A', 'B': 'new_B'})

49. How would you remove duplicates within a list in Python?


 my_list = [1, 2, 2, 3, 3, 4]
 unique_list = list(set(my_list))

50. Explain the “is” operator in Python. How does “is” differ from “==”?
 The "is" operator in Python is used to check if two variables refer to the same
object in memory, i.e., if they have the same memory address. It checks identity
rather than equality. On the other hand, the "==" operator is used to check if two
variables have the same value. "is" checks for object identity, while "==" checks
for equality of values.
 # Define two lists with the same values
 list1 = [1, 2, 3]
 list2 = [1, 2, 3]
 list3 = list2

 # Using "is" operator to check identity
 print(list1 is list2) # Output: False
 print(list3 is list2) # Output:True

 # Using "==" operator to check equality
 print(list1 == list2) # Output: True

51. What are some primitive data structures in Python? What are some user-defined data
structures?
 Some primitive data structures in Python include integers, floats, strings,
booleans, and None. User-defined data structures include lists, tuples, sets,
dictionaries, and custom classes.

52. When would you use NumPy arrays over Python lists?
NumPy arrays are preferred over Python lists when dealing with large datasets or
performing mathematical operations on arrays. NumPy arrays are more memory-
efficient and offer faster computation compared to Python lists.
53. What is data smoothing? How do you do it?
Data smoothing is a technique used to remove noise from a dataset by averaging
neighboring data points. It helps in identifying trends or patterns in the data.
Smoothing can be done using moving averages, Savitzky-Golay filters, or other
smoothing techniques.

54. Which Python libraries are most efficient for data processing?
Some efficient Python libraries for data processing include Pandas, NumPy, SciPy,
and scikit-learn. These libraries provide tools for data manipulation, analysis,
statistical modeling, and machine learning.

55. How can missing values be handled in Big Data?


Missing values in Big Data can be handled by imputation (replacing missing values
with a statistical measure such as mean, median, or mode), deletion (removing rows
or columns with missing values), or using advanced techniques like predictive
modeling to estimate missing values.

56. What is meant by outliers?


Outliers are data points that significantly differ from the rest of the data in a dataset.
They can skew statistical analysis and affect the accuracy of predictive models.
Outliers can be detected using statistical methods such as Z-score, IQR (Interquartile
Range), or visualization techniques like box plots.

57. What is meant by linear regression?


Linear regression is a statistical method used to model the relationship between a
dependent variable and one or more independent variables by fitting a linear equation
to the observed data. It is used for prediction and forecasting in various fields.
Let's say we want to predict the price of a house based on its size. We collect data on
house sizes (in square feet) and their corresponding prices. Using linear regression,
we fit a line to this data, where the size of the house is the independent variable (X)
and the price is the dependent variable (Y).

58. What is meant by logistic regression?


Logistic regression is a statistical method used for binary classification problems,
where the output variable is categorical with two possible outcomes. It models the
probability of a binary outcome based on one or more predictor variables.
Suppose we want to predict whether a student will pass or fail an exam based on the
number of hours they studied. We collect data on students' study hours and whether
they passed or failed the exam (coded as 1 for pass and 0 for fail). Using logistic
regression, we model the probability of passing the exam based on the number of
study hours. The logistic regression equation might look like:

59. What is the purpose of A/B testing?


A/B testing is a statistical hypothesis testing method used to compare two or more
versions of a product or service to determine which one performs better. It is
commonly used in marketing, web development, and product design to make data-
driven decisions.

60. What do you mean by collaborative filtering?


Collaborative filtering is a method used in recommendation systems to generate
personalized recommendations by analyzing user interactions and similarities between
users or items.

61. What are some biases that can happen while sampling?
Biases that can occur while sampling include selection bias, non-response bias, and
sampling bias. These biases can lead to inaccurate or skewed results in statistical
analysis

62. What is a distributed cache?


A distributed cache is a caching mechanism that stores data in memory across
multiple nodes in a distributed computing environment. It improves performance by
reducing access times to frequently accessed data.

63. How can you return the binary of an integer?


To return the binary of an integer in Python, you can use the built-in bin() function.
For example, bin(5) returns '0b101'.

64. What is the difference between append and extend in Python?


In Python, append() is used to add a single element to the end of a list, while
extend() is used to add multiple elements (such as elements of another list) to the end
of a list.
 append(4) adds the single element 4 to the end of the list my_list.
 extend([5, 6, 7]) adds the elements [5, 6, 7] (as a sequence) to the end of the list
my_list.

65. How can you check if a given string contains only letters and numbers?
To check if a given string contains only letters and numbers, you can use the
isalnum() method of strings. For example, "abc123".isalnum() returns True.

66. In Pandas, how can you create a dataframe from a list?


In Pandas, you can create a DataFrame from a list using the pd.DataFrame()
constructor. For example, df = pd.DataFrame(my_list) creates a DataFrame from a
list my_list.

67. How can you identify missing values in a data frame?


Missing values in a DataFrame can be identified using methods like isnull() or isna().
For example, df.isnull() returns a DataFrame of boolean values indicating missing
values.

68. Why do we make data frame in pandas?


DataFrames in Pandas are used to store and manipulate structured data in a tabular
format. They provide efficient data manipulation, integration with other libraries,
handling missing data, alignment, time series functionality, input/output operations,
and overall simplify data analysis tasks.

You might also like