Source: Safalta.com
1. Introduction to Digital Marketing
2. Website Planning and Creation
Top Python Interview Questions for Experienced ( 35 questions)
1. Could you explain what's wrong with the code below?
testProc([1, 2, 3]) # Explicitly passing in a list
testProc() # Using a default empty list
def testProc(n = []):
# Do something with n
print n
Ans.The code mentioned above would produce .
The variable n is private to the function testProc and is inaccessible from outside of it.
Therefore, printing it won't be an option.
2. What happens as a result of the Python code below?
class Test(object):
def __init__(self):
self.x = 1
t = Test()
print t.x
print t.x
print t.x
print t.x
Ans. Every print statement will show the number <1. This is due to the constant value of attribute(x) on objects.
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
1
1
1
1
Additionally, joins the Test class's public members.
As a result, direct access is possible.
3. Can you iterate over a list of words and use a dictionary to keep track of the frequency(count) of each word? Consider the below example.
{'Number':Frequency, '2':2, '3':2}
Ans. Please find out the below code.
def dic(words):
wordList = {}
for index in words:
try:
wordList[index] += 1
except KeyError:
wordList[index] = 1
return wordList
wordList='1,3,2,4,5,3,2,1,4,3,2'.split(',')
print wordList
print dic(wordList)
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
['1', '3', '2', '4', '5', '3', '2', '1', '4', '3', '2']
{'1': 2, '3': 3, '2': 3, '5': 1, '4': 2}
4.How could a list with duplicate entries be transformed into a list with unique elements?
Ans. It is not a good idea to iterate the list. The appropriate response should resemble this.
It is not a good idea to iterate the list. The appropriate response should resemble this.duplicates = ['a','b','c','d','d','d','e','a','b','f','g','g','h']
uniqueItems = list(set(duplicates))
print sorted(uniqueItems)
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
5.What is the outcome of the Python code below?
keyword = 'aeioubcdfg'
print keyword [:3] + keyword [3:]
Ans. The result of the code mentioned above is as follows.
<'aeioubcdfg'>
When cutting a string in Python, if the indices of the two slices coincide, a <+> operator get applied to concatenates them.
6.What are the effects of the lines of code below?
Here is a sample of the code.
def fast (items= []):
items.append (1)
return items
print fast ()
print fast ()
Ans. The result of the code mentioned above is as follows.
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
[1]
[1, 1]
After being defined, the function only evaluates its parameters once. However, since is a list, it will be changed by having a <1> appended to it.
7.What outcome does the following Python application produce?
Ans : The following is an example of code.
def multiplexers ():
return [lambda n: index * n for index in range (4)]
print [m (2) for m in multiplexers ()]
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
[6, 6, 6, 6]
The output of the above code is <[6, 6, 6, 6]>. The value of the variable is looked up after a call to any of the multiplexers functions, which is due to the late binding
8. Can you write code to determine if the provided object is a member of the class or a subclass of the class?
Ans. A method to list the instances of an object, which may include numerous classes, is built into Python. Instead of returning the individual classes, it returns a table of tuples. It has the following syntax.
The above method checks the presence of an object in one of the classes. The built-in types can also have many formats of the same function like or .
Additionally, employing the built-in classes is not advised. Instead, develop a user-defined class.
The example below can be used to identify the item belonging to a specific class.
Example.
def lookUp(obj):
if isinstance(obj, Mailbox):
print "Look for a mailbox"
elif isinstance(obj, Document):
print "Look for a document"
else:
print "Unidentified object"
9. Can you create Python code to find an object's name?
Ans. In Python, there are no names assigned to any objects. Therefore, there is no method to obtain the one for an item. All that the assignment does is connect a name to a value. The name would then only be able to refer to the value. Finding the object's reference name is the best we can do.
Example.
class Test:
def __init__(self, name):
self.cards = []
self.name = name
def __str__(self):
return '{} holds ...'.format(self.name)
obj1 = Test('obj1')
print obj1
obj2 = Test('obj2')
print obj2
10 . What Python copying techniques are you familiar with?
Ans. Commonly, we use or to perform copy operation on objects. Though not all objects support these methods but most do.
But some objects are easier to copy. Like the dictionary objects provide a method.
Example.
item = {n: n*2 for n in range(10)}
newdict = item.copy()
print newdict
11. What does it mean to randomise a list's entries while it is still in use?
Ans. A built-in module in Python is called "random." Any input sequence can be randomly generated by the public function shuffle("list").
import random
list = [2, 18, 8, 4]
print "Prior Shuffling - 0", list
random.shuffle(list)
print "After Shuffling - 1", list
random.shuffle(list)
print "After Shuffling - 2", list
12.What Python method splits a string the best?
Ans. With the help of the defined separator, we may split a string into substrings using themethod in Python. It gives back a list of all the words that were in the supplied string.
test = "I am learning Python."
print test.split(" ")
13. How should a Python string be converted into a list?
Ans. Strings are just like lists in Python. Additionally, turning a string into a list is simple. A string-to-list conversion would happen just by sending the string to the list as an argument.
list("I am learning Python.")
Program Output.
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
=> ['I', ' ', 'a', 'm', ' ', 'l', 'e', 'a', 'r', 'n', 'i', 'n', 'g', ' ', 'P', 'y', 't', 'h', 'o', 'n', '.']
14. What distinguishes Python's exception handling from Java's? List the optional Python clauses for a block as well?
Ans. Python implements exception handling slightly differently than Java does. It gives the programmer the choice to view the error information in a block rather than ending the programme. This statement occasionally includes a problem as well as a fix for the fault.
There are following clauses available in Python language.
1. try-except-finally
2. try-except-else
15. What are your understandings of the and comprehensions? Describe using an example.
Ans. The comprehensions offer a simpler method for producing the matching object using the current iterable. According to official Python documentation, list comprehensions typically run quicker than regular loops. However, it could vary between releases.
The Comprehensions Examples.
#Simple Iteration
item = []
for n in range(10):
item.append(n*2)
print item
16. How does Python manage its memory?
Ans. The Python Memory Manager is responsible for managing memory in Python. The memory that the manager allots to Python is in the form of a private heap area. This private heap is where all Python objects are kept and is unavailable to programmers. Python does, however, offer some fundamental API functions to operate with the private heap space.
Python also includes a built-in garbage collector to reuse any unused memory for the private heap area.
17. What are namespaces in Python? What is their purpose?
In Python, a namespace makes ensuring that object names are distinct and may be used without colliding. These namespaces are implemented by Python as dictionaries, where each "name as key" is translated to a corresponding "object as value." This makes it possible for various namespaces to map the same name to different objects while still using it. Here are a few instances of namespaces:
Within a function, local names are included in the Local Namespace. When a function is called, a temporary namespace is formed, and when the function completes, it is cleared.
Names from various imported packages and modules that are used in the current project are included in the Global Namespace. When a package is imported into a script, a namespace is generated that exists until the script is actually executed.
Built-in Namespace contains built-in Python core functions as well as built-in names for various exception types..
The lifecycle of a namespace depends upon the scope of objects they are mapped to. If the scope of an object ends, the lifecycle of that namespace comes to an end. Hence, it isn't possible to access inner namespace objects from an outer namespace.
18. Why are negative indices used? What are they?
The indices from the list, tuple, or string's end are known as negative indexes.
Ar[-1] means the last element of array Arr[]
arr = [1, 2, 3, 4, 5, 6]
#get the last element
print(arr[-1]) #output 6
#get the second last element
print(arr[-2]) #output 5
19. 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.
def tellArguments(**kwargs):
for key, value in kwargs.items():
print(key + ": " + value)
tellArguments(arg1 = "argument 1", arg2 = "argument 2", arg3 = "argument 3")
#output:
# arg1: argument 1
# arg2: argument 2
# arg3: argument 3
20. What are the Python join() and split() methods for?
To divide a string into a list of strings based on a delimiter, use the split() method.
A list of strings can be joined together using the join() function to produce a single string.
string = "This is a string."
string_list = string.split(' ') #delimiter is ‘space’ character or ‘ ‘
print(string_list) #output: ['This', 'is', 'a', 'string.']
print(' '.join(string_list)) #output: This is a string.
Use command os.remove(file_name)
import os
os.remove("ChangedFile.csv")
print("File Removed!")
21. What do Python iterators do?
An iterator is an object.
It remembers its state i.e., where it is during iteration (see code below to see how)
__iter__() method initializes an iterator.
It has a __next__() method which returns the next item in iteration and points to the next element. Upon reaching the end of iterable object __next__() must return StopIteration exception.
It is also self-iterable.
Iterators are objects with which we can iterate over iterable objects like lists, strings, etc.
class ArrayList:
def __init__(self, number_list):
self.numbers = number_list
def __iter__(self):
self.pos = 0
return self
def __next__(self):
if(self.pos < len(self.numbers)):
self.pos += 1
return self.numbers[self.pos - 1]
else:
raise StopIteration
array_obj = ArrayList([1, 2, 3])
it = iter(array_obj)
print(next(it)) #output: 2
print(next(it)) #output: 3
print(next(it))
#Throws Exception
#Traceback (most recent call last):
#...
#StopIteration
22. Python uses either a value or a reference to pass parameters.
Copy of the actual object is passed when you pass by value. The value of the original object will not change if the copy's value is altered.
Pass by reference: The real object is referenced while passing an object. The original object's value will change if the new object's value changes.
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]
23. How is Python translated?
Python is not an interpreted or compiled language. The implementation determines whether code is compiled or interpreted. Python is an interpretable bytecode (set of instructions that may be read by an interpreter).
The file with the.py extension is the source code.
Python converts the original code into a collection of virtual machine instructions. One implementation of that virtual machine is the Python interpreter. The.py source code is first compiled to produce.pyc, which is an intermediate format known as "bytecode." The official CPython or PyPy's JIT (Just in Time compiler) can then interpret this bytecode.
24. What distinguishes.py and.pyc files from one another?
The source code of an application can be found in.py files. .pyc files, however, contain your program's bytecode. After.py file compilation, we receive bytecode (source code). For some of the files you run,.pyc files are not generated. It is only made to go with the imported files.
The Python interpreter looks for the built files before running a programme. The virtual computer runs the file if it is there. If not, it searches for a.py file. If discovered, it is converted to a.pyc file and run on the Python virtual machine.
A.pyc file allows you to avoid the compilation process.
25.What does Python's PYTHONPATH mean?
You can add more directories to the PYTHONPATH environment variable, which instructs Python where to look for modules and packages. Maintaining Python libraries that you do not want to install in the global default location can be extremely helpful in this situation.
26.What do Python generators do?
Functions called generators return an iterable collection of elements one at a time and in a predetermined order. Iterators are often created using generators, each of which takes a distinct approach. Instead of using the return keyword to return a generator object, they utilise the yield keyword.
Let's attempt to create a fibonacci number generator.
## 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) # create generator object
## iterating using __next__(), for Python2, use next()
x.__next__() # output => 0
x.__next__() # output => 1
x.__next__() # output => 1
x.__next__() # output => 2
x.__next__() # output => 3
x.__next__() # output => 5
x.__next__() # output => 8
x.__next__() # error
## iterating using loop
for i in fib(10):
print(i) # output => 0 1 1 2 3 5 8
27. What exactly are pickling and unpickling?
Serialization is a feature that the Python library comes with by default. An object is "serialised" when it is converted into a format that can be stored in order to subsequently be "deserialized" and returned to its original state. The pickle module is used in this situation.
Pickling:
Python's serialisation procedure is known as pickling. In Python, any object can be serialised as a byte stream and stored in memory as a file. Although pickling is a compact procedure, pickled things can be compressed even more. Pickle also maintains a list of the objects it has serialised, and the serialisation is portable between versions.
Pickle.dump is the function used for the aforementioned procedure ().
Unpickling:
The exact opposite of pickling is unpickling. It loads the object into memory after deserializing the byte stream to reconstruct the objects saved in the file.
Pickle is the function utilised in the aforementioned process.
load().
28.What distinguishes Python's xrange and range functions?
Functionality-wise, xrange() and range() are fairly similar. The sole distinction between them is that range() gives a Python list, whereas xrange() returns an xrange object, and they both produce a sequence of integers.
So what difference does that make?
It most certainly does, as xrange() produces the value as it goes rather than generating a static list like range() does. This method, known as "yielding," is frequently employed with an object-type generator.
In applications where memory is a limited resource, yielding is essential. In these circumstances, creating a static list like in range() can result in a Memory Error, whereas xrange() can handle it best by utilising just enough memory for the generator (considerably less).
for i in xrange(10): # numbers from o to 9
print i # output => 0 1 2 3 4 5 6 7 8 9
for i in xrange(1,10): # numbers from 1 to 9
print i # output => 1 2 3 4 5 6 7 8 9
for i in xrange(1, 10, 2): # skip by two for next
print i # output => 1 3 5 7 9
Note: xrange has been deprecated as of Python 3.x. Now range does exactly the same as what xrange used to do in Python 2.x, since it was way better to use xrange() than the original range() function in Python 2.x.
29.In Python, how do you clone an object?
The assignment operator (=) in Python does not copy objects. Rather, it establishes a connection between the already-existing object and the desired variable name. In Python, we need to utilise the clone module to duplicate an object. Additionally, the copy module offers two options for making copies of the specified object:
Bit-wise copies of objects are known as shallow copies. The values of the original object are identically replicated in the cloned object. Only the reference addresses for the same object are replicated if either of the values is a reference to another object.
Deep Copy even duplicates the objects referenced because it replicates all values recursively from source to target 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]
30.What in Python is a lambda? Why is it employed?
Python's lambda function is an anonymous function that can take any number of parameters but only one expression. It is typically employed when a temporary anonymous function is called for. You can employ lambda functions in one of two ways:
Assigning lambda functions to a variable:
mul = lambda a, b : a * b
print(mul(2, 5)) # output => 10
Wrapping lambda functions inside another function:
def myWrapper(n):
return lambda a : a * n
mulFive = myWrapper(5)
print(mulFive(2)) # output => 10
31 What are comprehensions for dicta and lists?
Like decorators, Python comprehensions are syntactic sugar constructions that assist in creating modified and filtered versions of lists, dictionaries, or sets from a given list, dictionary, or set. Utilizing comprehensions cuts down on time and sometimes verbose code (containing more lines of code). Let's look at several situations when comprehensions can really help:
Performing mathematical operations on the entire list
my_list = [2, 3, 5, 7, 11]
squared_list = [x**2 for x in my_list] # list comprehension
# output => [4 , 9 , 25 , 49 , 121]
squared_dict = {x:x**2 for x in my_list} # dict comprehension
# output => {11: 121, 2: 4 , 3: 9 , 5: 25 , 7: 49}
Performing conditional filtering operations on the entire list
my_list = [2, 3, 5, 7, 11]
squared_list = [x**2 for x in my_list if x%2 != 0] # list comprehension
# output => [9 , 25 , 49 , 121]
squared_dict = {x:x**2 for x in my_list if x%2 != 0} # dict comprehension
# output => {11: 121, 3: 9 , 5: 25 , 7: 49}
Combining multiple lists into one
Comprehensions allow for multiple iterators and hence, can be used to combine multiple lists into one.
a = [1, 2, 3]
b = [7, 8, 9]
[(x + y) for (x,y) in zip(a,b)] # parallel iterators
# output => [8, 10, 12]
[(x,y) for x in a for y in b] # nested iterators
# output => [(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9)]
Flattening a multi-dimensional list
A similar approach of nested iterators (as above) can be applied to flatten a multi-dimensional list or work upon its inner elements.
my_list = [[10,20,30],[40,50,60],[70,80,90]]
flattened = [x for temp in my_list for x in temp]
# output => [10, 20, 30, 40, 50, 60, 70, 80, 90]
32 What do Python decorators do?
In essence, decorators in Python are functions that extend the capabilities of an already-existing function without altering the function's structure. In Python, they are denoted by the @decorator name and called bottom-up. For instance :
# decorator function to convert to lowercase
def lowercase_decorator(function):
def wrapper():
func = function()
string_lowercase = func.lower()
return string_lowercase
return wrapper
# decorator function to split words
def splitter_decorator(function):
def wrapper():
func = function()
string_split = func.split()
return string_split
return wrapper
@splitter_decorator # this is executed next
@lowercase_decorator # this is executed first
def hello():
return 'Hello World'
hello() # output => [ 'hello' , 'world' ]
The beauty of decorators resides in their ability to accept arguments for methods and further change those arguments before delivering them to the function itself, in addition to providing functionality to the method's output. The "wrapper" function, which is an inner nested function, is important in this situation. It is designed to uphold encapsulation and so maintain its privacy from the global scope.
# decorator function to capitalize names
def names_decorator(function):
def wrapper(arg1, arg2):
arg1 = arg1.capitalize()
arg2 = arg2.capitalize()
string_hello = function(arg1, arg2)
return string_hello
return wrapper
@names_decorator
def say_hello(name1, name2):
return 'Hello ' + name1 + '! Hello ' + name2 + '!'
say_hello('sara', 'ansh') # output => 'Hello Sara! Hello Ansh!'
33 .What does Python's Scope Resolution mean?
In some cases, objects with the same name but different functions exist in the same scope. Python automatically engages scope resolution in certain situations. Here are a few instances of similar conduct:
There are numerous functions found in both the math and cmath Python modules, such as log10(), acos(), and exp(). It is required to prefix them with their corresponding module, such as math.exp() and cmath.exp, in order to clear up this issue ().
Consider the code below, where a temporary object was initially initialised to 10 globally and to 20 upon calling a function. The function call did not, however, globally alter the temp's value. We can see that Python clearly distinguishes between global and local variables in this case by treating their namespaces as distinct entities.
temp = 10 # global-scope variable
def func():
temp = 20 # local-scope variable
print(temp)
print(temp) # output => 10
func() # output => 20
print(temp) # output => 10
This behavior can be overridden using the global keyword inside the function, as shown in the following example:
temp = 10 # global-scope variable
def func():
global temp
temp = 20 # local-scope variable
print(temp)
print(temp) # output => 10
func() # output => 20
print(temp) # output => 20