Python

Python Interview Questions and Answer

Q. What are the key features of Python?

A.

  1. -Interpreted Language:Programs written in an interpreted language runs directly from the source code, with no intermediary compilation step.
  2. - Free
  3. - Concise and simple
  4. - Object Oriented
  5. - Dynamically Typed - Python being an interpreted language, executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed language.
  6. - Has a large Community.

Q. What is the diference between list and tuple ?

A.

The main difference is that the List is Mutable and Tuple is not(Immutable). For more detail check here .

Q. What is PEP 8 ?

A.

PEP 8 is Python Enhancement Proposal

PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format Python code for maximum readability. PEP 8 is a coding convention that lets us write more readable code. In other words, it is a set of recommendations.

For ex. according to the official Python documentation, an identifier can be of any length. PEP 8 suggests that you should limit all lines to a maximum of 79 characters. Also, PEP 20 says 'readability counts'. So, a very long identifier will violate PEP-8 and PEP-20.

Q. What is the pass statement in Python?

A.

There may be times in our code when we haven't decided what to do yet, but we must type something for it to be syntactically correct. In such a case, we use the pass statement.

Q. Explain Python’s parameter-passing mechanism.

A.

To pass its parameters to a function, Python uses pass-by-reference. If you change a parameter within a function, the change reflects in the calling function. This is its default behavior. However, when we pass literal arguments like strings, numbers, or tuples, they pass by value. This is because they are immutable.

Q. What is the "with" statement in Python?

A.

The with statement in Python ensures that cleanup code is executed when working with unmanaged resources by encapsulating common preparation and cleanup tasks. It may be used to open a file, do something, and then automatically close the file at the end. It may be used to open a database connection, do some processing, then automatically close the connection to ensure resources are closed and available for others. "with" will cleanup the resources even if an exception is thrown. This statement is like the using statement in C#. Consider you put some code in a try block, then in the finally block, you close any resources used. The with statement is like syntactic sugar for that.

The syntax of this control-flow structure is:

with expression [as variable]:
….with-block

>>> with open('data.txt') as data:

Q. How is a .pyc file different from a .py file?

A.

While both files hold bytecode, .pyc is the compiled version of a Python file. It has platform-independent bytecode. Hence, we can execute it on any platform that supports the .pyc format. Python automatically generates it to improve performance(in terms of load time, not speed).

Q. Which is faster list or dictionary python ?

A.

Dictionaries. Membership testing is faster in dict than in list. Python dictionaries use hash tables, this means that a lookup operation (e.g., if x in y) is O(1). A lookup operation in a list means that the entire list needs to be iterated, resulting in O(n) for a list of length n.

Q. Are tuples faster than lists Python?

A.

Tuples are stored in a single block of memory. Tuples are immutalbe so, It doesn't require extraspace to store new objects. ... It is the reason creating a tuple is faster than List. It also explains the slight difference in indexing speed is faster than lists, because in tuples for indexing it follows fewer pointers.

Q. What are lambda functions in Python?

A.

Lambda is an anonymous function in Python, that can accept any number of arguments, but can only have a single expression. It is generally used in situations requiring an anonymous function for a short time period.

Syntax of Lambda Function in python

lambda arguments: expression
# Program to show the use of lambda functions
double = lambda x: x * 2

print(double(5))

This function has no name. It returns a function object which is assigned to the identifier double. We can now call it as a normal function.

For more details check here .

Q. Map function in Python ?

A.

The map() function in Python takes in a function and a list. map function executes the function given as the first argument on all the elements of the iterable given as the second argument. The function is called with all the items in the list and a new list is returned which contains items returned by that function for each item.

new_list = list(map(lambda x: x * 2 , my_list))

Q. Filter function in Python?

A.

The filter() function in Python takes in a function and a list as arguments.

The function is called with all the items in the list and a new list is returned which contains items for which the function evaluates to True.

new_list = list(filter(lambda x: (x%2 == 0) , my_list))

Q. What does the function zip() do?

A.

The purpose of zip() is to map the similar index of multiple containers so that they can be used just using as single entity.

zip() returns an iterator of tuples.

 >>> list(zip(['a','b','c'],[1,2,3]))
 
 [(‘a’, 1), (‘b’, 2), (‘c’, 3)]

Here, it pairs items from the two lists and creates tuples with those. But it doesn’t have to be lists.

 >>> list(zip(('a','b','c'),(1,2,3)))
 
 [(‘a’, 1), (‘b’, 2), (‘c’, 3)]

Q. How is memory managed in Python?

A.

Memory management in Python is handled by the Python Memory Manager. The memory allocated by the manager is in form of a private heap space dedicated for Python. All Python objects are stored in this heap, and being private, it is inaccessible to the programmer. Though, python does provide some core API functions to work upon the private heap space. Additionally, Python has an in-built garbage collection to recycle the unused memory for the private heap space.

Q. What is Python namespaces ?

A.

A namespace in Python ensures that object names in a program are unique and can be used without any conflict. Python implements these namespaces as dictionaries with 'name as key' mapped to a corresponding 'object as value'. This allows for multiple namespaces to use the same name and map it to a separate object. A few examples of namespaces are as follows:

Local Namespace includes local names inside a function. the namespace is temporarily created for a function call and gets cleared when the function returns.

Global Namespace includes names from various imported packages/modules that is being used in the current project. This namespace is created when the package is imported in the script and lasts until the execution of the script.

Built-in Namespace includes built-in functions of core Python and built-in names for various types of exceptions.

Q. What is a module in Python ?

A.

Modules, in general, are simply Python files with a .py extension and can have a set of functions, classes or variables defined and implemented Just stuff the modules into a folder and there you have it, the folder name as the package name. Importing a module or its contents from this package requires the package name as prefix to the module name joined by a dot.

Q. What are Global, protected and private attributes in Python ?

A.

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 a underscore prefixed to their identifier eg. _pro. 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. __pri. They cannot be accessed or modified from the outside directly and will result in an AttributeError if such an attempt is made.

Q. What is __init__?

A.

__init__ is a contructor method in Python and is automatically called to allocate memory when a new object/instance is created. All classes have a __init__ method associated with them.

Q. What does this mean: *args, **kwargs? And why would we use it?

A.

We use *args when we aren’t sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we don’t know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are a convention, you could also use *bob and **billy but that would not be wise.

Q. What is comprehension technique ?

A.

The signature for the list comprehension is as follows:

[ expression(var) for var in iterable ]

A dictionary has the same syntax as was for the list comprehension but the difference is that it uses curly braces:

adict = {var:var**2 for var in range(10, 20)}

The syntax for generator expression matches with the list comprehension, but the difference is that it uses parenthesis:

( expression(var) for var in iterable )

Q. What does the "self" keyword do?

A.

Self is a keyword in Python used to define an instance or an object of a class. In Python, it is explicitly used as the first paramter, unlike in Java where it is optional. It helps in disinguishing between the methods and attributes of a class from its local variables.

The self is a Python keyword which represents a variable that holds the instance of an object. In almost, all the object-oriented languages, it is passed to the methods as a hidden parameter.

Q. What is enumerate function ?

A.

The enumerate() function is used to iterate through the sequence and retrieve the index position and it's corresponding value at the same time.

 
>>> for i,v in enumerate(['Python','Java','C++']):
	print(i,v)

	
0 Python
1 Java
2 C++
>>>

Q. How do you do data abstraction in Python?

A.

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.

Q. Define encapsulation in Python?

A.

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

Q. What is Polymorphism in Python?

A.

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.

Q. Does python support multiple inheritance?

A.

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

Q. What is monkey patching in Python?

A.

In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.

Consider the below example:

# myModule.py
class MyClass:
def fun(self):
print("fun()")

We can then run the monkey-patch testing like this:

import myModule
def monkey_fun(self):
print("monkey_fun()")
 
myModule.MyClass.fun = monkey_fun
obj = myModule.MyClass()
obj.fun()

The output will be as below:

monkey_fun()

As we can see, we did make some changes in the behavior of fun() in MyClass using the function we defined, monkey_fun(), outside of the module myModule.

Q. What are generators in Python?

A.

Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object.

Let's try and build a generator for fibonacci numbers -

 ## generate fibonacci numbers upto n 
>>> def fib(n):
	p, q = 0, 1
	while(p < n):
		yield p
		p, q = q, p + q
>>> x=fib(10)
>>> x.__next__()
0
>>> x.__next__()
1
>>> x.__next__()
1
>>> x.__next__()
2
>>> x.__next__()
3
>>> x.__next__()
5
>>> x.__next__()
8
>>> x.__next__()
Traceback (most recent call last):
  File "", line 1, in 
    x.__next__()
StopIteration

>>> ## iterating using loop
>>> for i in fib(10):
	print(i) # output => 0 1 1 2 3 5 8

	
0
1
1
2
3
5
8
>>> 



Python if , elif and else

Python Conditions and If statements

  • 0
Python for beginners

Learning Python Part 1

  • 3
Struct Alignment and Padding

Struct Alignment and Padding in C++ And C

  • 0
Friend function

Friend function C++

  • 0
The diamond problem Solution C++

Solving the Diamond Problem with Virtual Inheritance

  • 0
Pointers

C++ Pointers

  • 0
Structures

C++ Structures

  • 0
Types of Inheritance in C++

Inheritance and access specifiers C++

  • 0
Java date pattern

Java Date Pattern Syntax

  • 0
Java Date and Calendar

Java Date formats

  • 0
JAVA Data Type

Data types in Java

  • 0
Java unreachable code

Unreachable Code Error in Java

  • 0
INTERVIEW EXPERIENCES

Articles

09

FEB

×

Forgot Password

Please enter your email address below and we will send you information to change your password.