Top 10 Most Asked Python Interview Questions With Answers Part 04

Top 10 Most Asked Python Interview Questions With Answers Part 03 By Muhammad Umair

Q.01 What Are The Types of Objects Support in Python Language?

Python supports are two types are of objects. They are:

Immutable built-in types:

Strings
Tuples
Numbers

Mutable built-in types:

List
Sets
Dictionaries
  • Immutable Objects
  • The objects which doesn’t allow to modify the contents of those objects are known as ‘Immutable Objects’
  • Before creating immutable objects with some content python interpreter verifies is already any object is available. In memory location with same content or not.
  • If already object is not available then python interpreter creates new objects with that content and store that object address two reference variable.
  • If already object is present in memory location with the same content creating new objects already existing object address will be given to the reference variable.
  • Program:
  • i=1000 print(i) print(type(i)) print(id(i)) j=2000 print(j) print(type(j)) print(id(j)) x=3000 print(x) print(type(x)) print(id(x)) y=3000 print(y) print(type(y)) print(id(y))
  • int, float, complex, bool, str, tuple are immutable objects
  • Immutable objects performance is high.
  • Applying iterations on Immutable objects takes less time.
  • All fundamentals types represented classes objects and tuple class objects are immutable objects.
  • Mutable Objects:
  1. The Objects which allows to modify the contents of those objects are known as ‘Mutable Objects’
  2. We can create two different mutable objects with same content
  • Program:
  • x=[10,20,30] print(x) print(type(x)) print(id(x)) y=[10,20,30] print(y) print(type(y)) print(id(y))
  • Output:
  • List, set, dict classes objects are mutable objects
  • Mutable objects performance is low when compared to immutable objects
    Applying Iterations mutable objects takes huge time

Q.02 Python is Call by Value or Call by Reference? How are arguments passed by value or by reference?

Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable.

Q.03 Explain Python’s parameter-passing mechanism.

  • 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.04 What are *args, **kwargs ?

In cases when we don’t know how many arguments will be passed to a function, like when we want to pass a list or a tuple of values, we use *args.

def func(*args):
for i in args:
print(i)

func(3,2,1,4,7)

3
2
1
4
7

**kwargs takes keyword arguments when we don't know how many there will be:

def func(**kwargs):
for i in kwargs:
print(i,kwargs[i])

func(a=1,b=2,c=7)

a.1
b.2
c.7

The words args and kwargs are a convention, and we can use anything in their place.

Q.05 How can I pass optional or keyword parameters from one function to another?

Collect the arguments using the and ** specifier in the function’s parameter list; this gives you the positional arguments as a tuple and the keyword arguments as a dictionary. You can then pass these arguments when calling another function by using `and**` :

def f(x, *tup, **kwargs):
kwargs['width']='14.3c'
g(x, *tup, **kwargs)

In the unlikely case that you care about Python versions older than 2.0, use ‘apply’:

def f(x, *tup, **kwargs):
kwargs['width']='14.3c'
apply(g, (x,)+tup, kwargs)

Q.06 What is lambda? What are Lambda Functions ?

A function which doesn’t contain any name is known as a anonymous function lambda function, Lambda function we can assign to the variable & we can call the lambda function through the variable.

Syntax: Lambda arguments:expression

It is a single expression anonymous function often used as inline function. A lambda form in python does not have statements as it is used to make new function object and then return them at runtime.

The lambda operator is used to create anonymous functions. It is mostly used in cases where one wishes to pass functions as parameters. or assign them to variable names.

When we want a function with a single expression, we can define it anonymously. A lambda expression may take input and returns a value. To define the above function as a lambda expression, we type the following code in the interpreter:

(lambda a,b:a if a>b else b)(3,3.5)

3.5

Here, a and b are the inputs.
a if a > b else b is the expression to return. The arguments are 3 and 3.5.

It is possible to not have any inputs here.

(lambda :print("Hi"))()

Hi

Example:

myfunction = lambda x:x*x
a = myfunction(10)
print(a)

Output: 100

  • Why can’t lambda forms in Python contain statements?

Lambdas evaluates at run time and these do not need statements Lambda is a anonymous function, which does not have a name and no fixed number of arguments. Represented by keyword lambda followed by statement. Ex:

add = lambda a,b: a+b
add(2,3)

output:
5

Q.07 How do you create your own package in Python?

It overrides the any initialization from an inherited class and is called when the class is instantiated.

We know that a package may contain sub-packages and modules. A module is nothing but Python code.
To create a package of our own, we create a directory and create a file __init__.py in it. We leave it empty. Then, in that package, we create a module(s) with whatever code we want. For a detailed explanation with pictures, refer to Python Packages.

Q.08 Explain the use “with” statement in python?

  • In python generally “with” statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. “with” statement makes the exception handling simpler by providing cleanup activities.

General form of with:

with open("filename", "mode") as file-var:

processing statements
Note: no need to close the file by calling close() upon file-var.close()

Q.09 What is Monkey patching ? Give example ?

Dynamically modifying a class or module at run-time.

class A:
def func(self):
print("Hi")
def monkey(self):
print "Hi, monkey"
m.A.func = monkey
a = m.A()
a.func()

Hi, monkey

Q.10 Explain serialization and deserialization / Pickling and unpicking.

Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

To create portable serialized representations of Python objects, we have the module ‘pickle’. It accepts a Python object (remember, everything in Python is an object). It then converts it into a string representation and uses the dump() function to dump it into a file. We call this pickling. In contrast, retrieving objects from this stored string representation is termed ‘unpickling’.

The pickle module implements binary protocols for serializing and deserializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as serialization, marshalling, or flattening; however, to avoid confusion, the terms used here are pickling and unpickling.

import json
json_string = json.dumps([1, 2, 3, "a", "b"])
print(json_string)

import pickle
pickled_string = pickle.dumps([1, 2, 3, "a", "b"])
print(pickle.loads(pickled_string))

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Muhammad Umair

Muhammad Umair

MERN Stack Developer | Software Engineer| Frontend & Backend Developer | Javascript, React JS, Express JS, Node JS, MongoDB, SQL, and Python