by BehindJava

Python Interview Questions Part 1

Home » python » Python Interview Questions Part 1

In this tutorial we are going to see important Python Interview Questions.

Q. How can you improve the following code?

import string

i = 0
for letter in string.letters:
    print("The letter at index %i is %s" % (i, letter))
    i = i + 1

Bonus points for mentioning enumerate and use of str.format.

Q. What is Python particularly good for? When is using Python the “right choice” for a project?

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.

Python is a high-level general-purpose programming language that can be applied to many different classes of problems.

The language comes with a large standard library that covers areas such as string processing like regular expressions, Unicode, calculating differences between files, Internet protocols like HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI programming, software engineering like unit testing, logging, profiling, parsing Python code, and operating system interfaces like system calls, file systems, TCP/IP sockets.

Although likes and dislikes are highly personal, a developer who is “worth his or her salt” will highlight features of the Python language that are generally considered advantageous (which also helps answer the question of what Python is “particularly good for”. Some of the more common valid answers to this question include:

  • Ease of use and ease of refactoring, thanks to the flexibility of Python’s syntax, which makes it especially useful for rapid prototyping.
  • More compact code, thanks again to Python’s syntax, along with a wealth of functionally-rich Python libraries (distributed freely with most Python language implementations).
  • A dynamically-typed and strongly-typed language, offering the rare combination of code flexibility while at the same time avoiding pesky implicit-type-conversion bugs.
  • It’s free and open source! Need we say more?

With regard to the question of when using Python is the “right choice” for a project, the complete answer also depends on a number of issues orthogonal to the language itself, such as prior technology investment, skill set of the team, and so on. Although the question as stated above implies interest in a strictly technical answer, a developer who will raise these additional issues in an interview will always “score more points” with me since it indicates an awareness of, and sensitivity to, the “bigger picture” (i.e., beyond just the technology being employed). Conversely, a response that Python is always the right choice is a clear sign of an unsophisticated developer.

Q. What are some drawbacks of the Python language?

For starters, if you know a language well, you know its drawbacks, so responses such as “there’s nothing I don’t like about it” or “it has no drawbacks” are very telling indeed.

The two most common valid answers to this question (by no means intended as an exhaustive list) are:

  • The Global Interpreter Lock (GIL). CPython (the most common Python implementation) is not fully thread safe. In order to support multi-threaded Python programs, CPython provides a global lock that must be held by the current thread before it can safely access Python objects. As a result, no matter how many threads or processors are present, only one thread is ever being executed at any given time.
  • In comparison, it is worth noting that the PyPy implementation discussed earlier in this article provides a stackless mode that supports micro-threads for massive concurrency.

Execution speed. Python can be slower than compiled languages since it is interpreted. (Well, sort of. See our earlier discussion on this topic.)

Q. We know Python is all the rage these days. But to be truly accepting of a great technology, you must know its pitfalls as well.

Of course. To be truly yourself, you must be accepting of your flaws. Only then can you move forward to work on them. Python has its flaws too:

Python’s interpreted nature imposes a speed penalty on it. While Python is great for a lot of things, it is weak in mobile computing, and in browsers.

Being dynamically-typed, Python uses duck-typing (If it looks like a duck, it must be a duck). This can raise runtime errors.

Python has underdeveloped database access layers. This renders it a less-than-perfect choice for huge database applications.

And even after these pitfalls, of course. Being easy makes it addictive. Once a Python-coder, always a Python coder.

So while it has problems, it is also a wonderful tool for a lot of things.

Q. What are the key differences between Python 2 and 3?

Division operator
`print` function  
Unicode 
xrange  
Error Handling  
`_future_` module

Although Python 2 is formally considered legacy at this point,its use is still widespread enough that is important for a developer to recognize the differences between Python 2 and 3.

Here are some of the key differences that a developer should be aware of:

Text and Data instead of Unicode and 8-bit strings. Python 3.0 uses the concepts of text and (binary) data instead of Unicode strings and 8-bit strings. The biggest ramification of this is that any attempt to mix text and data in Python 3.0 raises a TypeError (to combine the two safely, you must decode bytes or encode Unicode, but you need to know the proper encoding, e.g. UTF-8)

This addresses a longstanding pitfall for naïve Python programmers. In Python 2, mixing Unicode and 8-bit data would work if the string happened to contain only 7-bit (ASCII) bytes, but you would get UnicodeDecodeError if it contained non-ASCII values. Moreover, the exception would happen at the combination point, not at the point at which the non-ASCII characters were put into the str object. This behavior was a common source of confusion and consternation for neophyte Python programmers.

print function. The print statement has been replaced with a print() function

xrange – buh-bye. xrange() no longer exists (range() now behaves like xrange() used to behave, except it works with values of arbitrary size)

API changes:

  • zip(), map() and filter() all now return iterators instead of lists.
  • dict.keys(), dict.items() and dict.values() now return ‘views’ instead of lists.
  • dict.iterkeys(), dict.iteritems() and dict.itervalues() are no longer supported.
  • Comparison operators. The ordering comparison operators (<, <=, >=, >) now raise a TypeError exception when the operands don’t have a meaningful natural ordering. Some examples of the ramifications of this include:
  • Expressions like 1 < ”, 0 > None or len <= len are no longer valid
  • None < None now raises a TypeError instead of returning False
  • Sorting a heterogeneous list no longer makes sense.
  • All the elements must be comparable to each other

Q. What are some key differences to bear in mind when coding in Python vs. Java?

Disclaimer #1. The differences between Java and Python are numerous and would likely be a topic worthy of its own (lengthy) post. Below is just a brief sampling of some key differences between the two languages.

Disclaimer #2. The intent here is not to launch into a religious battle over the merits of Python vs. Java (as much fun as that might be!). Rather, the question is really just geared at seeing how well the developer understands some practical differences between the two languages. The list below therefore deliberately avoids discussing the arguable advantages of Python over Java from a programming productivity perspective.

With the above two disclaimers in mind, here is a sampling of some key differences to bear in mind when coding in Python vs. Java:

Dynamic vs static typing: One of the biggest differences between the two languages is that Java is restricted to static typing whereas Python supports dynamic typing of variables.

Static vs. class methods: A static method in Java does not translate to a Python class method.

In Python, calling a class method involves an additional memory allocation that calling a static method or function does not.

In Java, dotted names (e.g., foo.bar.method) are looked up by the compiler, so at runtime it really doesn’t matter how many of them you have. In Python, however, the lookups occur at runtime, so “each dot counts”.

Method overloading: Whereas Java requires explicit specification of multiple same-named functions with different signatures, the same can be accomplished in Python with a single function that includes optional arguments with default values if not specified by the caller.

Single vs. double quotes. Whereas the use of single quotes vs. double quotes has significance in Java, they can be used interchangeably in Python (but no, it won’t allow beginnning the same string with a double quote and trying to end it with a single quote, or vice versa!).

Getters and setters (not!). Getters and setters in Python are superfluous; rather, you should use the ‘property’ built-in (that’s what it’s for!). In Python, getters and setters are a waste of both CPU and programmer time.

Classes are optional. Whereas Java requires every function to be defined in the context of an enclosing class definition, Python has no such requirement.

Indentation matters… in Python. This bites many a newbie Python programmer.

The Big Picture

  • An expert knowledge of Python extends well beyond the technical minutia of the language. A Python expert will have an in-depth understanding and appreciation of Python’s benefits as well as its limitations. Accordingly, here are some sample questions that can help assess this dimension of a candidate’s expertise.

Q. What will be the output of the code below in Python 2?

def div1(x,y):
    print "%s/%s = %s" % (x, y, x/y)
def div2(x,y):
    print "%s//%s = %s" % (x, y, x//y)

div1(5,2)
div1(5.,2)
div2(5,2)
div2(5.,2.)

Also, how would the answer differ in Python 3 (assuming, of course, that the above [print] statements were converted to Python 3 syntax)?

-  kjalfkjaslf

Q. What is the difference between range and xrange? How has this changed over time?

As follows:

  • xrange returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is.
  • For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please.
  • The only difference is that range returns a Python list object and x range returns an xrange object. This means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function to use.
  • This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It’s a memory hungry beast.

Q. What will be the output of the code below?

List = ['a', 'b', 'c', 'd', 'e']
print(list[10:])

TypeError: ‘type’ object is not subscriptable if proper name given,it will print [].

Q. What is a method?

A method is a function on some object x that you normally call as x.name(arguments…). Methods are defined as functions inside the class definition:

class C: 
    def meth (self, arg): 
        return arg*2 + self.attribute

Q. How do I call a method defined in a base class from a derived class that overrides it?

If you’re using new-style classes, use the built-in super() function:

class Derived(Base):
    def meth (self): 
       super(Derived, self).meth() 

If you’re using classic classes: For a class definition such as class Derived(Base): … you can call method meth() defined in Base (or one of Base’s base classes) as Base.meth(self,arguments). Here, Base.meth is an unbound method, so you need to provide the self argument.

Q. How can I organize my code to make it easier to change the base class?

You could define an alias for the base class, assign the real base class to it before your class definition, and use the alias throughout your class. Then all you have to change is the value assigned to the alias. Incidentally, this trick is also handy if you want to decide dynamically (e.g. depending on availability of resources) which base class to use.

Example: BaseAlias = class Derived(BaseAlias): def meth(self): BaseAlias.meth(self).

Q. How do I find the current module name?

A module can find out its own module name by looking at the predefined global variable name. If this has the value ’main’, the program is running as a script. Many modules that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking name:

def main():
    print('Running test...')
if __name__ == '__main__':
    main() 
__import__('x.y.z')
returns Try: __import__('x.y.z').y.z

# For more realistic situations, you may have to do something like:
m = __import__(s) 
	for i in s.split(".")[1:]: m = getattr(m, i) 

Q. How do I access a module written in Python from C?

You can get a pointer to the module object as follows:

module = PyImport_ImportModule("");

If the module hasn’t been imported yet (i.e. it is not yet present in sys.modules), this initializes the module; otherwise it simply returns the value of sys.modules[""]. Note that it doesn’t enter the module into any namespace — it only ensures it has been initialized and is stored in sys.modules. You can then access the module’s attributes (i.e. any name defined in the module) as follows: attr = PyObjectGetAttrString(module, ""); Calling PyObjectSetAttrString() to assign to variables in the module also works.

Q. How do I convert a number to a string?

To convert, e.g., the number 144 to the string ‘144’, use the built-in function str(). If you want a hexadecimal or octal representation, use the built-in functions hex() or oct(). For fancy formatting, use the % operator on strings, e.g. “%04d” % 144 yields ‘0144’ and “%.3f” % (1/3.0) yields ‘0.333’. See the library reference manual for details.

Q. How is the Implementation of Python’s dictionaries done?

Python dictionary needs to be declared first:

dict = {}

Key value pair can be added as:

dict[key] = value or

objDict.update({key:value})

Remove element by:

dict.pop(key)

Remove all:

objDict.clear()

A hash value of the key is computed using a hash function, The hash value addresses a location in an array of “buckets” or “collision lists” which contains the (key , value) pair.

Q. What is used to create Unicode string in Python?

“u” should be added before the string

a = (u’Python’)
type(a) #will give you unicode

Add unicode before the string. Ex: unicode(text) resulting in text.

Q. What is the built-in function used in Python to iterate over a sequence of numbers?

Syntax: range(start,end,step count)

Ex:

a = range(1,10,2)
print (a)
Output:
[1, 3, 5, 7, 9]

If using to iterate

for i in range(1,10):
    print (i)
Output:

1\
2\
3\
4\
5\
6\
7\
8\
9

Q. Does Python have a switch-case statement?

Ans. In languages like C++, we have something like this:

switch(name)
{
    case 'Ram':
        cout<<"Monday";
        break;
    case 'Shiv':
        cout<<"Tuesday";
        break;
    default:
        cout<<"Hi, user";
}

But in Python, we do not have a switch-case statement. Here, you may write a switch function to use. Else, you may use a set of if-elif-else statements. To implement a function for this, we may use a dictionary.

def switch(choice):     
    switcher={
        'Ram':'Monday',
        'Shiv':'Tuesday',
        print(switcher.get(choice,'Hi, user'))
    return 
    switch('Shiv')
    Tuesday
    switch('Ram')
    Monday
    switch('Raghav')
    Hi, user
    }

Here, the get() method returns the value of the key. When no key matches, the default value (the second argument) is returned.

Q. Does python support switch or case statement in Python? If not what is the reason for the same?

Dictionary can be used as case/switch. Actually there is no switch statement in the Python programming language but the is a similar construct that can do justice to switch that is the exception handling using try and except1,except2,except3… and so on.

Q. What is the statement that can be used in Python if a statement is required syntactically but the program requires no action?

pass keyword is used to do nothing but it fulfill the syntactical requirements.

try x[10]:
    print(x)
except:
    pass

Use pass keyword over there like:

if a > 0:
    print("Hello")
else:
    pass

Q. Does Python support strongly for regular expressions?

Yes, Python Supports Regular Expressions Well. re is an in-buit library for the same. There is a lot of other languages that have good support to RegEx- Perl, Awk, Sed, Java etc.

Regular expressions (called REs, or regexes, or regex patterns) are essentially a tiny, highly specialized programming language embedded inside Python and made available through the re module. Using this little language, you specify the rules for the set of possible strings that you want to match; this set might contain English sentences, or e-mail addresses, or TeX commands, or anything you like. You can then ask questions such as “Does this string match the pattern?”, or “Is there a match for the pattern anywhere in this string?“. You can also use REs to modify a string or to split it apart in various ways.

Regular expression patterns are compiled into a series of bytecodes which are then executed by a matching engine written in C. For advanced use, it may be necessary to pay careful attention to how the engine will execute a given RE, and write the RE in a certain way in order to produce bytecode that runs faster. Optimization isn’t covered in this document, because it requires that you have a good understanding of the matching engine’s internals.

Q. How do you perform pattern matching in Python? Explain.

Regular Expressions/REs/ regexes enable us to specify expressions that can match specific “parts” of a given string. For instance, we can define a regular expression to match a single character or a digit, a telephone number, or an email address, etc. The Python’s “re” module provides regular expression patterns and was introduce from later versions of Python 2.5. “re” module is providing methods for search text strings, or replacing text strings along with methods for splitting text strings based on the pattern defined.

Q. Write a regular expression that will accept an email id. Use the re module. Ans.

import re   
e = re.search(r'[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$' 'JaiRameshwar@gmail.com')
e.group()
'Ramayanwashere@gmail.com'

To brush up on regular expressions, check Regular Expressions in Python.

Garbage Collector & Memory Manager

Q. What is Garbage Collection?

The concept of removing unused or unreferenced objects from the memory location is known as a Garbage Collection. While executing the program, if garbage collection takes place then more memory space is available for the program and rest of the program execution becomes faster.

Garbage collector is a predefined program, which removes the unused or unreferenced objects from the memory location.

Any object reference count becomes zero then we call that object as a unused or unreferenced object Then no.of reference variables which are pointing the object is known as a reference count of the object.

While executing the python program if any object reference count becomes zero, then internally python interpreter calls the garbage collector and garbage collector will remove that object from memory location.

Q. How is memory managed in Python?

Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter. Like other programming language python also has garbage collector which will take care of memory management in python.Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space. The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code.

Python has a private heap space to hold all objects and data structures. Being programmers, we cannot access it; it is the interpreter that manages it. But with the core API, we can access some tools. The Python memory manager controls the allocation.

Q. Why isn’t all memory freed when Python exits?

Objects referenced from the global namespaces of Python modules are not always deallocated when Python exits. This may happen if there are circular references. There are also certain bits of memory …

Q. Whenever you exit Python, is all memory de-allocated? State why is it so.

The answer here is no. The modules with circular references to other objects, or to objects referenced from global namespaces, aren’t always freed on exiting Python. Plus, it is impossible to de-allocate portions of memory reserved by the C library.

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.It is impossible to de-allocate those portions of memory that are reserved by the C library.On exit, because of having its own efficient clean up mechanism, Python would try to de-allocate/destroy every other object.

Q. Is it possible to assign multiple var to values in list?

The multiple assignment trick is a shortcut that lets you assign multiple variables with the values in a list in one line of code. So instead of doing this:

cat = ['fat', 'orange', 'loud']
size = cat[0]
color = cat[1]
disposition = cat[2] 

Do this:

cat = ['fat', 'orange', 'loud']
size, color, disposition = cat

Q. What is slots and when is it useful?

In Python, every class can have instance attributes. By default Python uses a dict to store an object’s instance attributes. This is really helpful as it allows setting arbitrary new attributes at runtime.

However, for small classes with known attributes it might be a bottleneck. The dict wastes a lot of RAM. Python can’t just allocate a static amount of memory at object creation to store all the attributes. Therefore it sucks a lot of RAM if you create a lot of objects. The usage of slots to tell Python not to use a dict, and only allocate space for a fixed set of attributes.

Example:

  1. Object without slots

    class MyClass(object):
      def __init__(self, *args, **kwargs):
                self.a = 1
                self.b = 2

if name == ”main”: instance = MyClass() print(instance.dict)

2. Object with slots
```js
class MyClass(object):
      __slots__=['a', 'b']
      def __init__(self, *args, **kwargs):
                self.a = 1
                self.b = 2
  
if __name__ == "__main__":
     instance = MyClass()
     print(instance.__slots__)

Q. 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. 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. 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. 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. 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. 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

Q. 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. 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. 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. 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. 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))

Reference: [1] https://www.sanfoundry.com/python-questions-answers-pickle-module/ [2] https://docs.python-guide.org/scenarios/serialization/

Q. What are higher ordered functions?

You have two choices: you can use nested scopes or you can use callable objects. For example, suppose you wanted to define linear(a,b) which returns a function f(x) that computes the value a*x+b. Using nested scopes:

def linear(a,b): 
    def result(x): 
        return a*x + b 
            return result

Or

using a callable object:

class linear: 
    def __init__(self, a, b):
        self.a, self.b = a,b 
        def __call__(self, x): 
            return self.a * x + self.b 

In both cases:

taxes = linear(0.3,2) gives a callable object where

taxes(10e6) == 0.3 * 10e6 + 2.

The callable object approach has the disadvantage that it is a bit slower and results in slightly longer code. However, note that a collection of callables can share their signature via inheritance:

class exponential(linear): 
    __init__ inherited
    def __call__(self, x):
        return self.a * (x ** self.b) 

Object can encapsulate state for several methods:

class counter: 
    value = 0 
    def set(self, x): 
        self.value = x 
    def up(self): 
        self.value=self.value+1 
    def down(self): 
        self.value=self.value-1 
        count = counter() 

inc, dec, reset = count.up, count.down, count.set Here inc(), dec() and reset() act like functions which share the same counting variable.

Q. How do I copy a file? How to copy object in Python? Diff between shallow copy and deep copy?

The shutil module contains a copyfile() function.

A deep copy copies an object into another. This means that if you make a change to a copy of an object, it won’t affect the original object. In Python, we use the function deepcopy() for this, and we import the module copy. We use it like:

import copy
b = copy.deepcopy (a)

A shallow copy, however, copies one object’s reference to another. So, if we make a change in the copy, it will affect the original object. For this, we have the function copy(), we use it like:

b = copy.copy(a)

Q. Differentiate between lists and tuples.

The major difference is that a list is mutable, but a tuple is immutable. Examples:

Traceback (most recent call last):

File "<pyshell#97>", line 1, in  mytuple[1]=2
TypeError: 'tuple' object does not support item assignment

Q. What is the purpose of PYTHONSTARTUP, PYTHONCASEOK, PYTHONHOME & PYTHONPATH environment variables?

  • PYTHONSTARTUP − It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH.
  • PYTHONCASEOK − It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.
  • PYTHONHOME − It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.
  • PYTHONPATH − It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.

Q. Explain Inheritance in Python with an example.

When one class inherits from another, it is said to be the child/ derived/sub class inheriting from the parent/base/super class. It inherits/gains all members (attributes and methods). Inheritance lets us reuse our code, and also makes it easier to create and maintain applications.

Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability,makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived/child class.

They are different types of inheritance supported by Python:

Single Inheritance – where a derived class acquires the members of a single super class.

OR

Single Inheritance- A class inherits from a single base class.

Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 is inherited from base2.

OR

Multilevel Inheritance- A class inherits from a base class, which in turn, inherits from another base class.

Hierarchical inheritance – from one base class you can inherit any number of child classes

OR

Hierarchical Inheritance- Multiple classes inherit from a single base class.

Multiple inheritance – a derived class is inherited from more than one base class.

OR

Multiple Inheritance- A class inherits from multiple base classes.

Hybrid Inheritance- Hybrid inheritance is a combination of two or more types of inheritance.

Q. What is Hierarchical Inheritance?

The concept of inheriting the properties from one class into multiple classes separately is known as hierarchical inheritance.

Example:

class x(object):    
    def m1(self):       
        print("in m1 of x")

class y(x):     
    def m2(self):   
        print("in m2 of y")

class z(x): 
    def m3(self):   
        print("in m3 of z")
y1=y()
y1.m1()
y1.m2()
a=y1.--hash--()
print(a)
z1=z()
z1.m1()
z1.m3()
b=z1.hash--()
print(b)
Output:

M m1 of X 
In m2 of Y
2337815
In m1 of X
In m3 of Z
2099735

Q. Suppose class C inherits from classes A and B as class C(A,B).Classes A and B both have their own versions of method func(). If we call func() from an object of class C, which version gets invoked?

Ans. In our article on Multiple Inheritance in Python, we discussed Method Resolution Order (MRO). C does not contain its own version of func(). Since the interpreter searches in a left-to-right fashion, it finds the method in A, and does not go to look for it in B.

Q. Which methods/functions do we use to determine the type of instance and inheritance?

Ans. Here, we talk about three methods/functions- type(), isinstance() and issubclass().

a. type(): This tells us the type of object we’re working with.

type(3)

<class 'int'>

type(False)

<class 'bool'>

type(lambda :print(“Hi”))

<class 'function'>

type(type)

<class 'type'>

b. isinstance()

This takes in two arguments- a value and a type. If the value is of the kind of the specified type, it returns True. Else, it returns False.

 isinstance(3,int)

True

 isinstance((1),tuple)

False

 isinstance((1,),tuple)

True

c. issubclass()

This takes two classes as arguments. If the first one inherits from the second, it returns True. Else, it returns False.

 class A: pass
 class B(A): pass
 issubclass(B,A)
True

 issubclass(A,B)
False

Q. Write a one-liner that will count the number of capital letters in a file. Your code should work even if the file is too big to fit in memory.

Let us first write a multiple line solution and then convert it to one liner code.

with open(SOME_LARGE_FILE) as fh:
    count = 0
    text = fh.read()    
for character in text:
    if character.isupper():
        count += 1

Q. Write a sorting algorithm for a numerical dataset in Python. The following code can be used to sort a list in Python:

list = ["1", "4", "0", "6", "9"]
list = [int(i) for i in list]
list.sort()
print(list)

Q. How will you remove last object from a list?

list.pop(obj=list[-1]) − Removes and returns last object or obj from list.

Q. What are negative indexes and why are they used?

Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.

The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ that is uses as first index and ‘1’ as the second index and the process goes on like that.

The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number.

The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order.

Let’s take a list for this.

mylist=[0,1,2,3,4,5,6,7,8]

A negative index, unlike a positive one, begins searching from the right.

mylist[-3]
6

This also helps with slicing from the back:

mylist[-6:-1]
[3, 4, 5, 6, 7]

Q. Explain split(), sub(), subn() methods of re module in Python.

To modify the strings, Python’s “re” module is providing 3 methods. They are:

  1. split() – uses a regex pattern to “split” a given string into a list.
  2. sub() – finds all substrings where the regex pattern matches and then replace them with a different string.
  3. subn() – it is similar to sub() and also returns the new string along with the no. of replacements.

Q. What is map function in Python?

Map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given. #Follow the link to know more similar functions

Q. How to get indices of N maximum values in a NumPy array?

We can get the indices of N maximum values in a NumPy array using the below code:

import numpy as np
arr = np.array([1, 3, 2, 4, 5])
print(arr.argsort()[-3:][::-1])

Q. What is a Python module?

A module is a Python script that generally contains import statements, functions, classes and variable definitions, and Python runnable code and it “lives” file with a ‘.py’ extension. zip files and DLL files can also be modules.Inside the module, you can refer to the module name as a string that is stored in the global variable name .

Q. Name the File-related modules in Python?

Python provides libraries / modules with functions that enable you to manipulate text files and binary fileson file system. Using them you can create files, update their contents, copy, and delete files. The librariesare : os, os.path, and shutil.

Here,

  • os and os.path – modules include functions for accessing the filesystem
  • shutil – module enables you to copy and delete the files.

Q. How many kinds of sequences are supported by Python? What are they?

Python supports 7 sequence types. They are str, list, tuple, unicode, byte array, xrange, and buffer. where xrange is deprecated in python 3.5.X.

Q. How to display the contents of text file in reverse order?How will you reverse a list?

list.reverse() − Reverses objects of list in place, convert the given file into a list. Reverse the list by using reversed(). E.g.:

for line in reversed(list(open("file-name","r"))):
     print(line)

Q. What is the difference between NumPy and SciPy?

In an ideal world, NumPy would contain nothing but the array data type and the most basic operations: indexing, sorting, reshaping, basic element wise functions, et cetera. All numerical code would reside in SciPy. However, one of NumPy’s important goals is compatibility, so NumPy tries to retain all features supported by either of its predecessors. Thus NumPy contains some linear algebra functions, even though these more properly belong in SciPy. In any case, SciPy contains more fully-featured versions of the linear algebra modules, as well as many other numerical algorithms. If you are doing scientific computing with python, you should probably install both NumPy and SciPy. Most new features belong in SciPy rather than NumPy.

Q. Which of the following is an invalid statement?

a) abc = 1,000,000 b) a b c = 1000 2000 3000 c) a,b,c = 1000, 2000, 3000 d) abc = 1,000,000 Answer: b

Q. What is the output of the following?

try: 
    if '1' != 1: 
        raise

a) some Error has occured
b) some Error has not occured
c) invalid code
d) none of the above

Answer: C

Q. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1] ?

25

Q. How to open a file c:\scores.txt for writing?

fileWriter = open("c:\\scores.txt", "w")

Q. Name few Python modules for Statistical, Numerical and scientific computations ? numPy – this module provides an array/matrix type, and it is useful for doing computations on arrays.

scipy – this module provides methods for doing numeric integrals, solving differential equations, etc.

pylab – is a module for generating and saving plots

Q. What is TkInter?

TkInter is Python library. It is a toolkit for GUI development. It provides support for various GUI tools or widgets (such as buttons, labels, text boxes, radio buttons, etc) that are used in GUI applications. The common attributes of them include Dimensions, Colors, Fonts, Cursors, etc.

Q. Is Python object oriented? what is object oriented programming?

Yes. Python is Object Oriented Programming language. OOP is the programming paradigm based on classes and instances of those classes called objects. The features of OOP are: Encapsulation, Data Abstraction, Inheritance, Polymorphism.

Q. Does Python supports interfaces like in Java? Discuss.

Python does not provide interfaces like in Java. Abstract Base Class (ABC) and its feature are provided by the Python’s “abc” module. Abstract Base Class is a mechanism for specifying what methods must be implemented by its implementation subclasses. The use of ABC’c provides a sort of “understanding” about methods and their expected behaviour. This module was made available from Python 2.7 version onwards.

Q. What are Accessors, mutators, @property?

Accessors and mutators are often called getters and setters in languages like “Java”. For example, if x is a property of a user-defined class, then the class would have methods called setX() and getX(). Python has an @property ‘decorator’ that allows you to ad getters and setters in order to access the attribute of the class.

Q. Differentiate between append() and extend() methods.?

Both append() and extend() methods are the methods of list. These methods are used to add the elements at the end of the list.

  1. append(element) – adds the given element at the end of the list which has called this method.
  2. extend(another-list) – adds the elements of another-list at the end of the list which is called the extend method.

Q. Name few methods that are used to implement Functionally Oriented Programming in Python?

Python supports methods (called iterators in Python3), such as filter(), map(), and reduce(), that are very useful when you need to iterate over the items in a list, create a dictionary, or extract a subset of a list.

  • filter() – enables you to extract a subset of values based on conditional logic.
  • map() – it is a built-in function that applies the function to each item in an iterable.
  • reduce() – repeatedly performs a pair-wise reduction on a sequence until a single value is computed.

Q. What is the output of the following?

x = ['ab', 'cd']
print(len(map(list, x)))
A TypeError occurs as map has no len().

Q. What is the output of the following?

x = ['ab', 'cd']
print(len(list(map(list, x))))
The length of each string is 2.

Q. Which of the following is not the correct syntax for creating a set?

a) set([[1,2],[3,4]]) b) set([1,2,2,3,4]) c) set((1,2,3,4)) d) {1,2,3,4}

A.
Explanation : The argument given for the set must be an iterable.

Q. Explain a few methods to implement Functionally Oriented Programming in Python.

Sometimes, when we want to iterate over a list, a few methods come in handy.

filter(): Filter lets us filter in some values based on conditional logic.

list(filter(lambda x:x>5,range(8)))

Ans: [6, 7]

map(): Map applies a function to every element in an iterable.

list(map(lambda x:x**2,range(8)))

Ans: [0, 1, 4, 9, 16, 25, 36, 49]

reduce(): Reduce repeatedly reduces a sequence pair-wise until we reach a single value

from functools import reduce
reduce(lambda x,y:x-y,[1,2,3,4,5])

Ans: -13

Q. Write a Python function that checks whether a passed string is palindrome Or not?

Note: A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam , saas, nun.

def isPalindrome(string):
    left_pos = 0
    right_pos = len(string)1

    while right_pos >= left_pos:
        if not string[left_pos] == string[right_pos]:
            return False

    left_pos += 1
    right_pos -= 1
    return True
print(isPalindrome('aza'))

Q. Write a Python program to calculate the sum of a list of numbers.

def list_sum(num_List):
    if len(num_List) == 1:
        return num_List[0]
    else:
        return num_List[0] + list_sum(num_List[1:])
print(list_sum([2, 4, 5, 6, 7]))

Sample Output: 24

Q. How to retrieve data from a table in MySQL database through Python code? Explain.

#import MySQLdb module as : 
import MySQLdb

#establish a connection to the database.
db = MySQLdb.connect("host"="local host", "database-user"="user-name", "password"="password","database-name"="database")

#initialize the cursor variable upon the established connection: 
c1 = db.cursor()

#retrieve the information by defining a required query string.
s = "Select * from dept"

#fetch the data using fetch() methods and print it. 
data = c1.fetch(s)

#close the database connection. 
db.close()

Q. Write a Python program to read a random line from a file.

import random
def random_line(fname):
    lines = open(fname).read().splitlines()
    return random.choice(lines)
    print(random_line('test.txt'))

Q. Write a Python program to count the number of lines in a text file.

def file_lengthy(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
        return i + 1

print("Number of lines in the file: ",file_lengthy("test.txt"))