Friday, 2 September 2016

Python Interview Questions

The following python questions are being asked in interviews.

1. What are the Data structures used in python?

   The following are the Data structures used in the python.
  
    1. List []
    2. Dictionary{}
    3. tuples()
    4. sets
   
2. What do you mean by List comprehension in python?

   List Comprehensions are easy way to create new lists
   Common applications are to make new lists where each element is the result of some
   operations applied to each member of another sequence.
  
 List comprehensions example 1:
 
   newlist =[]
   oldlist = [9,8,7,6,5]
    for i in oldlist:
        if (i%2==0) :
           newlist.append(i)

    print newlist
   
    The above example can be written in a single using List comprehension.
   
    newlist = [i for i in oldlist if(i%2 ==0)]

    print newlist
   
output:
[8,6]
   
 List comprehensions example 2:
 
newlist = []
for x in [1,2,3]:
   for y in [3,1,4]:
      if x != y:
        newlist.append((x, y))

(or)
List comphrehension as:

newlist = [(i,j) for i in [1,2,3] for j in [3,1,4] if x!=y]

Output ->
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

3. What is Lambda or Anonymous function?

Lambda is also called as Anonymous function. Anonymous means "function without a name".
Lambda is one line mini functions which are created on FLY. or
These creates new function objects on fly with out using "DEF" keywords or Function body.

Examples of Lambda:
def fun(a)
  return(a*2)
 
fun(2)

or
fun = lambda a: a*2

fun(2)

or
//Pass the 3 as argument
y =(lambda a: a*2 (3))

print y

4. What is difference between List and Tuple?

Understand the Immutable Types and mutable types.

Mutable means it can be changed , Immutable means it can't be changed.

Mutable types are lists and dictionaries

Immutable types are tuples, int, string.

List can be changed by append or extend or insert action functions.

Whereas in tuples the values can't be changed. That's a reason it can be used as keys in Dictionaries.

a=[1,3,4,5,6,7,8]
a.append(10)
print a   -> [1,3,4,5,6,7,8,10]

a=[1,3,4,5,6,7,8]
b=[11,12,13]
a.extend(b)
print a   -> [1,3,4,5,6,7,8,11,12,13]

a =(1,2,3,4)

Basic Operations in Tuples:
len((1, 2, 3))      3               Length
(1, 2, 3) + (4, 5, 6)      (1, 2, 3, 4, 5, 6)               Concatenation
('Hi!',) * 4       ('Hi!', 'Hi!', 'Hi!', 'Hi!')               Repetition
3 in (1, 2, 3)       True               Membership
for x in (1, 2, 3): print x,       1 2 3               Iteration


5. How to define a class in python?

Class is a collection of objects

Simple Syntax of class:
-----------------------
class Classname:
  < class Variables>      -- Shared by all objects (Class Instances)
 
  < Class methods :>
 
E.g:
 class Base:
    var = 9
   
    # Constructor
    def __init__(self):
       var = 9           -- Unique to the object
       print "constructor is called"
   
    def method1(self):
       print "muni"
   
    def method2(self)
       print "sekhar"
   
    def method3(self):
       self.var = self.var +3   -- Instance variable (unique to objects)
      
if __name__=="main":
   
    obj = base()   // Constructor is called
   
    obj.method1()  // Call the method1
   
6. How to define the private variable in Python Class?

There are two ways to make variables as private in python. 
(_ single underscore (weak Private), "__" double underscore (Strong Private)


> Single underscore  ( _variable) -> weak private, it can accessed outside in the same file.
   But other module will not have access to these variables.

> Double underscore  ( __variable) ->strong private, it can't be accessed outside in the same file.
   Other module will not have access to these variables.

   There is a way to access these varibles. < objectName>._<class name>__<double underscore variable>

Sample Example
=============

class Myclass(object):

    # Weak private variable ( With single Underscore)
    _singleUnderscoreVariable=0

    # Strong private Variable (With Double Underscore)
    __doubleUnderscoreVariable=0

    # Constructor
    def __init__(self):
       Myclass._singleUnderscoreVariable += 1
       Myclass.__doubleUnderscoreVariable +=1

    def printData(self):
       print "Single underscore: %d" % Myclass._singleUnderscoreVariable
       print "Instance variable: %d" % Myclass.__doubleUnderscoreVariable

if __name__ =="__main__":

   # Object 1 Created
   m_object = Myclass()

   # print data
   m_object.printData();

   # single underscore variable can be accessed
   # But it can't be imported
   print m_object._singleUnderscoreVariable

7. How to define the private method in Python Class?

  The main purpose of having private method in python class is to restrict the function
  to import to other modules (files)
 
  This can be done in two ways Single underscore or Double underscore.
 
  Single Underscore ("_")  -> Weak private-> can't be accessed out side the file.
  But it can be accessed outside the class. (Like a protected)
 
  Double Underscore ("__")  -> strong Private. It can't be accessed outside class or File.
  It can be accessed only in class method.

8. What is overriding? How to achieve overriding in python?
Method Overriding concept basically used in the inheritance.  Method Overriding means the parent class method is overridden by the child class.

In other words, both parent class and child class have same method (same name, parameters etc.)

In python, the method overriding is simple. There is no need to use the Keyword called "virtual" as in C++.

Overriding in python is pretty straight forward. Check the below example.

class Base(object):

    def override(self):
        print "Base Class override()"

class Derived(Base):

    def override(self):
        print "Derived class override()"

# Create Base class Object
baseObj = Base()

# Create Derived class Object
derivedObj = Derived()

# Call the base class method using baseObj
baseObj.override()

# Call the Derived class method using derivedObj:
# Derived class is overriding the method of base class
derivedObj.override()

 
9. Explain the memory Management in Python?
 
  The memory in the python is managed by private Heap. The memory manager stores the python objects and data structures in private Heap.
 
  Programmer may not have access to the private Heap. Python also have inbuilt GARBAGE collector.
 
  GARBAGE COLLECTOR works on the algorithm called "REFERENCE COUNTING".
    If the reference count is zero ( or no one refers to the object/variable) then that memory will be recycled and added to the heap.
 
  Good Answer from Stack Over Flow:
 
  How are variables and memory managed in Python?

     Automagically! No, really, you just create an object and the Python Virtual Machine handles the memory needed and where it shall be placed in the memory layout.

  Does it have a stack and a heap and what algorithm is used to manage memory?

    Memory management in Python involves a private heap containing all Python objects and data structures.
    The management of this private heap is ensured internally by the Python memory manager.
    The Python memory manager has different components which deal with various dynamic storage management aspects, like sharing, segmentation, preallocation or caching.
    The algorithm used for garbage collecting is called Reference counting. That is the Python VM keeps an internal journal of how many references refer to an object, and automatically garbage collects it when there are no more references referring to it. 


10. What is Constructor? How to declare constructor in class?

Constructor is used to initialize the object data members of a class.
Constructors can be overloaded , it means zero argument constructor, one argument constructor, two argument constructor etc...


Constructor is called during object creation.

class Base:
 
  def __init__(self):
    print " base class Constructor is called"

 
baseObj = Base()   # Zero Argument or Default constructor
#baseObj = Base(1) # One  Argument constructor


11.  How to share global variables across modules in python?

The global variables can be shared across the modules using "IMPORT"

 "import" the module and access the variable using the <ModuleName>.<variableName>

  The efficient way of doing as.  <Source from Python documentation>  


The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).   Just import the config module in all modules of your application; the module then becomes available as a global name.  Because there is only one instance of each module, any changes made to the module object get reflected everywhere.
 

For example:
  

config.py:

x = 0   # Default value of the 'x' configuration setting (Global variable)
mod.py:

import config
config.x = 1


main.py:

import config
import mod
print config.x


12. Explain about Python is a call by reference or Call by value?

Python is neither Call by reference or Call by value.

Everything in python is a object. We can call it as CALL-BY-OBJECT or CALL-BY-OBJECT Reference.

Check out the below examples for Better Understanding:

Immutable Types are String, Int, tuples.
Mutable Types are List, dictionaries.

Example 1:  < Source from Stack Overflow>

If you are passing a variable, then it's pass by value,
which means the changes made to the variable within the function are local to that function and
hence won't be reflected globally. This is more of a 'C/C++' like behavior.

def stringFunc(testString):
    testString="New_Value"
    print "Inside function" % testString

String_Old="Old_Value"
stringFunc(String_Old)
print "Outside function" % String_Old


Output: Inside function New_Value
             Outside function Old_Value

       
Example 2:

If you are passing the variables packed inside a mutable object, like a list or dictionaries
then the changes made to the object are reflected globally as long as the object is not re-assigned.

def changelist( mylist ):
   mylist2=['a'];
   mylist.append(mylist2);
   print "values inside the function: ", mylist
   return

mylist = [1,2,3];
changelist( mylist );
print "values outside the function: ", mylist


O/P:

values inside the function:  [1, 2, 3, ['a']]
values outside the function:  [1, 2, 3, ['a']]


Example 3:

Now consider the case where the object is re-assigned.
In this case, the object refers to a new memory location which is local to the function in
which this happens and hence not reflected globally.

def changelist( mylist ):
   mylist=['a'];
   print "values inside the function: ", mylist
   return

mylist = [1,2,3];
changelist( mylist );
print "values outside the function: ", mylist


O/P:

values inside the function:  ['a']
values outside the function:  [1, 2, 3]



Note:
     If you want to be able to change your values with a function call, what you need is a mutable object (List or Dictionaries).

Interesting Example:

test_string = 'Muni'

first_list = []
first_list.append(test_string)

second_list = first_list
second_list.append('Output String')
test_string = 'Reddy'

print (test_string, first_list, second_list)


Output->
Reddy, ['Muni', 'Output String'], ['Muni', 'Output String']

From the above example it is evident that :
Assignment between lists (second_list = first_list) does not create a new object. Rather, both lists are simply bound to the same object.
As a result, the string object and list object are still the only objects that have been created by the interpreter.

This brings us to an important point: there are actually two kinds of objects in Python. A mutable object exhibits time-varying behavior.
Changes to a mutable object are visible through all names bound to it.
Python's lists are an example of mutable objects. An immutable object does not exhibit time-varying behavior.


13. How to pass list,  tuples and dictionaries as arguments in the functions (Methods)?
  
List can be passed like a normal variable (e.g: arg)
Tuples can be passed as single star (*)  (e.g: *args)
Dictionaries can be passed as double star (**) (e.g: **kwargs)

Check the examples below:

List:
------
def listFunc(arg):
   print arg

#List Variable
listVar = [1,2,3,4,5]

listFunc(listVar)

Tuples:
---------
def tuplesfunc(*args):
   print args

#Tuple Variable
tupleVar = (1,2,3,4)

tuplesfunc(*tupleVar)

# or
tuplesfunc(1,2,3,4,5)


Output:
(1, 2, 3, 4)
(1, 2, 3, 4, 5)


Dictionaries:
---------------
def dictFunc(**kwargs):
   print kwargs


#Dictionary Variable
DictVar =  {'student_name': 'muni', 'school_name' : 'SAI', 'ID':2}

dictFunc(**DictVar)

# or

dictFunc(ID=1, school_name='sai', student_name='muni')

output:
{'student_name': 'muni', 'school_name': 'SAI', 'ID': 2}
{'student_name': 'muni', 'ID': 1, 'school_name': 'sai'} 

How to use all in single function?

Order of using *args **kwargs and formal args

If you want to use all three of these in functions then the order is
some_func(fargs,*args,**kwargs)

14. What is Split() and Join() Methods in Python?


If you want to use all three of these in functions then 

Split()  - Returns a list by seperating the elements based on the delimiter.  (Returns List)
-------
Example:
testString = "This,is,the,test,string"
testString.split(',')

Output:
['This', 'is', 'the', 'test', 'string']

Join()
------
str.Join() - Method returns a string This method returns a string.
Which is the concatenation of the strings in the sequence seq.
The separator between elements is the string providing this method.

e.x:
"".join(testString)

Output-> 'This,is,the,test,string'


e.x:
"-".join(testString)
Output-> 'T-h-i-s-,-i-s-,-t-h-e-,-t-e-s-t-,-s-t-r-i-n-g'


Simple Problem:

Take a string testString="Iam,the,best,person" as input and generate output as  Iam-the-best-person

testString="Iam,the,best,person"
output = "-".join((testString.split(",")))
print output

8 comments:

  1. Core Python interview questions and answers for freshers and 1 to 5 years experience candidate.Learn tips and tricks for cracking Python interviews.Coding tag will guide you the best e-learning website that cover all technical and learn technical tutorial based on different languages.

    ReplyDelete
  2. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! 统计作业代写

    ReplyDelete
  3. Thanks for sharing all the information with us all.
    python Online Training

    ReplyDelete
  4. Learn How to create a nested webpage in HTML with a step-by-step guide using iframe and embed tag.

    ReplyDelete