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

Python Interview Questions

The document provides an overview of various Python concepts including the __init__ constructor, differences between arrays and lists, slicing, control flow statements (break, continue, pass), and the use of self. It also explains attributes (global, protected, private), modules, argument passing, memory management, and new features in Python 3.9. Additionally, it covers advanced topics like lambda functions, multithreading, inheritance, polymorphism, encapsulation, and data abstraction.
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 views10 pages

Python Interview Questions

The document provides an overview of various Python concepts including the __init__ constructor, differences between arrays and lists, slicing, control flow statements (break, continue, pass), and the use of self. It also explains attributes (global, protected, private), modules, argument passing, memory management, and new features in Python 3.9. Additionally, it covers advanced topics like lambda functions, multithreading, inheritance, polymorphism, encapsulation, and data abstraction.
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/ 10

1. What is __init__?

__init__ is a contructor method in Python and is automatically called to allocate memory


when a new object/instance is created.

2. What is the difference between Python Arrays and lists?

 Arrays in python can only contain elements of same data types i.e., data type of array should be
homogeneous. It is a thin wrapper around C language arrays and consumes far less memory than
lists.
 Lists in python can contain elements of different data types i.e., data type of lists can be
heterogeneous. It has the disadvantage of consuming large memory.

4. What is slicing in Python?

 As the name suggests, ‘slicing’ is taking parts of.


 Syntax for slicing is [start : stop : step]

7. What is break, continue and pass in Python?

Break The break statement terminates the loop immediately and the control flows to the
statement after the body of the loop.

Continue The continue statement terminates the current iteration of the statement, skips the rest
of the code in the current iteration and the control flows to the next iteration of the loop.

Pass As explained above, the pass keyword in Python is generally used to fill up empty blocks
and is similar to an empty statement represented by a semi-colon in languages such as
Java, C++, Javascript, etc.

8. What is the use of self in Python?

Self is used to represent the instance of the class. With this keyword, you can access the
attributes and methods of the class in python.

9. What are global, protected and private attributes in Python?

 Global variables are public variables that are defined in the global scope. To use the variable
in the global scope inside a function, we use the global keyword.
 Protected attributes are attributes defined with an underscore prefixed to their identifier eg.
_sara. They can still be accessed and modified from outside the class they are defined in but a
responsible developer should refrain from doing so.
 Private attributes are attributes with double underscore prefixed to their identifier eg. __ansh.
They cannot be accessed or modified from the outside directly and will result in an
AttributeError if such an attempt is made.

10. What are modules and packages in Python?


Python packages and Python modules are two mechanisms that allow for modular
programming in Python. Modularizing has several advantages -

 Simplicity: Working on a single module helps you focus on a relatively small portion of the
problem at hand. This makes development easier and less error-prone.
 Maintainability: Modules are designed to enforce logical boundaries between different
problem domains. If they are written in a manner that reduces interdependency, it is less
likely that modifications in a module might impact other parts of the program.
 Reusability: Functions defined in a module can be easily reused by other parts of the
application.
 Scoping: Modules typically define a separate namespace, which helps avoid confusion
between identifiers from other parts of the program.

9. What does *args and **kwargs mean?

*args

 *args is a special syntax used in the function definition to pass variable-length arguments.
 “*” means variable length and “args” is the name used by convention. You can use any other.

def multiply(a, b, *argv):


mul = a * b
for num in argv:
mul *= num
return mul
print(multiply(1, 2, 3, 4, 5)) #output: 120

**kwargs

 **kwargs is a special syntax used in the function definition to pass variable-length


keyworded arguments.
 Here, also, “kwargs” is used just by convention. You can use any other name.
 Keyworded argument means a variable that has a name when passed to a function.
 It is actually a dictionary of the variable names and its value.

12. How are arguments passed by value or by reference in python?

 Pass by value: Copy of the actual object is passed. Changing the value of the copy of the
object will not change the value of the original object.
 Pass by reference: Reference to the actual object is passed. Changing the value of the new
object will change the value of the original object.

In Python, arguments are passed by reference, i.e., reference to the actual object is passed.

def appendNumber(arr):
arr.append(4)
arr = [1, 2, 3]
print(arr) #Output: => [1, 2, 3]
appendNumber(arr)
print(arr) #Output: => [1, 2, 3, 4]

14. What is the difference between .py and .pyc files?


 .py files contain the source code of a program. Whereas, .pyc file contains the bytecode of
your program. We get bytecode after compilation of .py file (source code). .pyc files are not
created for all the files that you run. It is only created for the files that you import.

20. How do you copy an object in Python?

In Python, the assignment statement (= operator) does not copy objects. Instead, it creates a
binding between the existing object and the target variable name. To create copies of an
object in Python, we need to use the copy module. Moreover, there are two ways of creating
copies for the given object using the copy module -

Shallow Copy is a bit-wise copy of an object. The copied object created has an exact copy of
the values in the original object. If either of the values is a reference to other objects, just the
reference addresses for the same are copied.
Deep Copy copies all values recursively from source to target object, i.e. it even duplicates
the objects referenced by the source object.

from copy import copy, deepcopy


list_1 = [1, 2, [3, 5], 4]
## shallow copy
list_2 = copy(list_1)
list_2[3] = 7
list_2[2].append(6)
list_2 # output => [1, 2, [3, 5, 6], 7]
list_1 # output => [1, 2, [3, 5, 6], 4]
## deep copy
list_3 = deepcopy(list_1)
list_3[3] = 8
list_3[2].append(7)
list_3 # output => [1, 2, [3, 5, 6, 7], 8]
list_1 # output => [1, 2, [3, 5, 6], 4]
Q9.What are Dict and List comprehensions?

Ans: Dictionary and list comprehensions are just another concise way to define
dictionaries and lists.

Example of list comprehension is-

x=[i for i in range(5)]

The above code creates a list as below-

[0,1,2,3,4]

Example of dictionary comprehension is-

x=[i : i+2 for i in range(5)]

The above code creates a list as below-

[0: 2, 1: 3, 2: 4, 3: 5, 4: 6]

Q14.What are Literals in Python and explain about different Literals


Ans: A literal in python source code represents a fixed value for primitive data types.
There are 5 types of literals in python-

1. String literals– A string literal is created by assigning some text enclosed in


single or double quotes to a variable. To create multiline literals, assign the
multiline text enclosed in triple quotes. Eg.name=”Tanya”
2. A character literal– It is created by assigning a single character enclosed in
double quotes. Eg. a=’t’
3. Numeric literals include numeric values that can be either integer, floating
point value, or a complex number. Eg. a=50
4. Boolean literals– These can be 2 values- either True or False.
5. Literal Collections– These are of 4 types-

a) List collections-Eg. a=[1,2,3,’Amit’]

b) Tuple literals- Eg. a=(5,6,7,8)

c) Dictionary literals- Eg. dict={1: ’apple’, 2: ’mango, 3: ’banana`’}

d) Set literals- Eg. {“Tanya”, “Rohit”, “Mohan”}

6. Special literal- Python has 1 special literal None which is used to return a null
variable.

Q15.What are the new features added in Python 3.9.0.0 version?

Ans: The new features in Python 3.9.0.0 version are-

 New Dictionary functions Merge(|) and Update(|=)


 New String Methods to Remove Prefixes and Suffixes
 Type Hinting Generics in Standard Collections
 New Parser based on PEG rather than LL1
 New modules like zoneinfo and graphlib
 Improved Modules like ast, asyncio, etc.
 Optimizations such as optimized idiom for assignment, signal handling,
optimized python built ins, etc.
 Deprecated functions and commands such as deprecated parser and symbol
modules, deprecated functions, etc.
 Removal of erroneous methods, functions, etc.

Q16. How is memory managed in Python?

Ans: Memory is managed in Python in the following ways:

1. Memory management in python is managed by Python private heap space.


All Python objects and data structures are located in a private heap. The
programmer does not have access to this private heap. The python interpreter
takes care of this instead.
2. The allocation of heap space for Python objects is done by Python’s memory
manager. The core API gives access to some tools for the programmer to
code.
3. Python also has an inbuilt garbage collector, which recycles all the unused
memory and so that it can be made available to the heap space.

Q17. What is namespace in Python?

Ans: A namespace is a naming system used to make sure that names are unique to
avoid naming conflicts.

Q22.What is type conversion in Python?

Ans: Type conversion refers to the conversion of one data type into another.

int() – converts any data type into integer type

float() – converts any data type into float type

ord() – converts characters into integer

hex() – converts integers to hexadecimal

oct() – converts integer to octal

tuple() – This function is used to convert to a tuple.

set() – This function returns the type after converting to set.

list() – This function is used to convert any data type to a list type.

dict() – This function is used to convert a tuple of order (key, value) into a dictionary.

str() – Used to convert integer into a string.

complex(real,imag) – This function converts real numbers to complex(real,imag)


number.

Q28.What is a lambda function?

Ans: An anonymous function is known as a lambda function. This function can have
any number of parameters but, can have just one statement.

Example:

a = lambda x,y : x+y

print(a(5, 6))
Q32. How can you randomize the items of a list in place in Python?

from random import shuffle


x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High']
shuffle(x)
print(x)

Q44. What is the usage of help() and dir() function in Python?

Ans:Help() and dir() both functions are accessible from the Python interpreter and
used for viewing a consolidated dump of built-in functions.

1. Help() function: The help() function is used to display the documentation


string and also facilitates you to see the help related to modules, keywords,
attributes, etc.
2. Dir() function: The dir() function is used to display the defined symbols.

Q45. Whenever Python exits, why isn’t all the memory de-allocated?

Ans:

1. Whenever Python exits, especially those Python modules which are having
circular references to other objects or the objects that are referenced from the
global namespaces are not always de-allocated or freed.
2. It is impossible to de-allocate those portions of memory that are reserved by
the C library.
3. On exit, because of having its own efficient clean up mechanism, Python
would try to de-allocate/destroy every other object.

Q47. How can the ternary operators be used in python?

Ans:The Ternary operator is the operator that is used to show the conditional
statements. This consists of the true or false values with a statement that has to be
evaluated for it.

Syntax:

The Ternary operator will be given as:


[on_true] if [expression] else [on_false]

x, y = 25, 50

big = x if x < y else y

Q53. How can files be deleted in Python?


Ans: To delete a file in Python, you need to import the OS Module. After that, you
need to use the os.remove() function.

Example:

import os
os.remove("xyz.txt")
Q56.How to add values to a python array?

Ans: Elements can be added to an array using the append(), extend() and
the insert (i,x) functions.

Q57. How to remove values to a python array?

Ans: Array elements can be removed using pop() or remove() method. The
difference between these two functions is that the former returns the deleted value
whereas the latter does not.

Q59. What is the difference between deep and shallow copy?

Ans:Shallow copy is used when a new instance type gets created and it keeps the
values that are copied in the new instance. Shallow copy is used to copy the
reference pointers just like it copies the values. These references point to the original
objects and the changes made in any member of the class will also affect the original
copy of it. Shallow copy allows faster execution of the program and it depends on the
size of the data that is used.

Deep copy is used to store the values that are already copied. Deep copy doesn’t
copy the reference pointers to the objects. It makes the reference to an object and
the new object that is pointed by some other object gets stored. The changes made
in the original copy won’t affect any other copy that uses the object. Deep copy
makes execution of the program slower due to making certain copies for each object
that is been called.

Q60. How is Multithreading achieved in Python?

Ans:

1. Python has a multi-threading package but if you want to multi-thread to speed


your code up, then it’s usually not a good idea to use it.
2. Python has a construct called the Global Interpreter Lock (GIL). The GIL
makes sure that only one of your ‘threads’ can execute at any one time. A
thread acquires the GIL, does a little work, then passes the GIL onto the next
thread.
3. This happens very quickly so to the human eye it may seem like your threads
are executing in parallel, but they are really just taking turns using the same
CPU core.
4. All this GIL passing adds overhead to execution. This means that if you want
to make your code run faster then using the threading package often isn’t a
good idea.
Q74. Does python support multiple inheritance?

Ans: Multiple inheritance means that a class can be derived from more than one
parent classes. Python does support multiple inheritance, unlike Java.

Q75. What is Polymorphism in Python?

Ans: Polymorphism means the ability to take multiple forms. So, for instance, if the
parent class has a method named ABC then the child class also can have a method
with the same name ABC having its own parameters and variables. Python allows
polymorphism.

Q76. Define encapsulation in Python?

Ans: Encapsulation means binding the code and the data together. A Python class
in an example of encapsulation.

Q77. How do you do data abstraction in Python?

Ans: Data Abstraction is providing only the required details and hiding the
implementation from the world. It can be achieved in Python by using interfaces and
abstract classes.

Q79. How to create an empty class in Python?

Ans: An empty class is a class that does not have any code defined within its block. It can
be created using the pass keyword. However, you can create objects of this class outside
the class itself. IN PYTHON THE PASS command does nothing when its executed. it’s a null
statement.
For example-
class a:
pass
obj=a()
obj.name="xyz"
print("Name = ",obj.name)

5) What is PEP 8?
The Python Enhancement Proposal, also known as PEP 8, is a document
that provides instructions on how to write Python code. In essence, it is a
set of guidelines for formatting Python code for maximum readability.

Striping
- Strip
- Lstrip - rstrip
42) What is the usage of enumerate () function in Python?
The enumerate() function is used to iterate through the sequence and
retrieve the index position and its corresponding value at the same time.

Example:

1. list_1 = ["A","B","C"]
2. s_1 = "Javatpoint"
3. # creating enumerate objects
4. object_1 = enumerate(list_1)
5. object_2 = enumerate(s_1)
6.
7. print ("Return type:",type(object_1))
8. print (list(enumerate(list_1)))
9. print (list(enumerate(s_1)))

Output:

Return type: <class 'enumerate'>


[(0, 'A'), (1, 'B'), (2, 'C')]
[(0, 'J'), (1, 'a'), (2, 'v'), (3, 'a'), (4, 't'), (5, 'p'), (6, 'o'), (7,
'i')
2. What are the benefits of using Python language as a tool in the
present scenario?
The following are the benefits of using Python language:
 Object-Oriented Language
 High-Level Language
 Dynamically Typed language
 Extensive support Libraries
 Presence of third-party modules
 Open source and community development
 Portable and Interactive
 Portable across Operating systems
3. Is Python a compiled language or an interpreted language?
Actually, Python is a partially compiled language and partially interpreted
language. The compilation part is done first when we execute our code
and this will generate byte code internally this byte code gets converted
by the Python virtual machine(p.v.m) according to the underlying
platform(machine+operating system).
7. What is the difference between a Set and Dictionary?
The set is an unordered collection of data types that is iterable, mutable
and has no duplicate elements.
A dictionary in Python is an ordered collection of data values, used to
store data values like a map.
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.
 In Python 3, there is no xrange, but the range function behaves like
xrange.
 In Python 2
o range() – This returns a range object, which is an immutable
sequence type that generates the numbers on demand.
o xrange() – This function returns the generator object that can
be used to display numbers only by looping. The only
particular range is displayed on demand and hence called lazy
evaluation.
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.
31. How do you debug a Python program?
By using this command we can debug a Python program:
$ python -m pdb python-script.py
39. How to delete a file using Python?
We can delete a file using Python by following approaches:
 os.remove()
 os.unlink()
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.

You might also like