Python Interview Questions And Answers

Python interview questions and answers on advance and basic Python with example so this page for both freshers and experienced condidate. Fill the form below we will send the all interview questions on Python also add your Questions if any you have to ask and for apply in Python Tutorials and Training course just send a mail on in detail about your self.

Top Python interview questions and answers for freshers and experienced

What is Python ?

Answer :

Questions : 1 :: what is Python's slice notation?

Python slicing is a computationally fast way to methodically access parts of your data. In my opinion, to be even an intermediate Python programmer, it's one aspect of the language that it is...View answers

Questions : 2 :: What is Python? State some programming language features of Python.

Python is a modern powerful interpreted language with objects, modules, threads, exceptions, and automatic memory managements. Python was introduced to the world in the year 1991 by Guido...View answers

Questions : 3 :: Explain how python is interpreted.

Python program runs directly from the source code. Each type Python programs are executed code is required. Python converts source code written by the programmer into intermediate language which is...View answers

Questions : 4 :: What are the rules for local and global variables in Python?

If a variable is defined outside function then it is implicitly global. If variable is assigned new value inside the function means it is local. If we want to make it global we need to explicitly...View answers

Questions : 5 :: How do I test one variable against multiple values?

You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for: if x...View answers

Questions : 6 :: How do you split a list into evenly sized chunks in Python?

Here's a generator that yields the chunks you want: def chunks(l, n):""" Yield successive n-sized chunks from l. """for i in xrange(0, len(l), n):yield l[i:i+n] import...View answers

Questions : 7 :: Python list of lists, changes reflected across sublists unexpectedly

When you write [x]*3 you get, essentially, the list [x, x, x]. That is, a list with 3 references to x. When you then change x all three references are changed. To fix it, you need to make sure...View answers

Questions : 8 :: How do I pass a variable by reference?

Arguments are passed by assignment. The rationale behind this is twofold: the parameter passed in is actually a reference to an object (but the reference is passed by value) some data types are...View answers

Questions : 9 :: What does the yield keyword do in Python?

To understand what yield does, you must understand what generators are. And before generators come iterables. Iterables When you create a list, you can read its items one by one, and it's called...View answers

Questions : 10 :: Calling an external command in Python

Look at the subprocess module in the stdlib: from subprocess import call call(["ls","-l"]) The advantage of subprocess vs system is that it is more flexible (you can get the stdout, stderr,...View answers

Questions : 11 :: Flatten (an irregular) list of lists in Python

Using generator functions can make your example a little easier to read and probably boost the performance. def flatten(l):for el in l:if isinstance(el, collections.Iterable)andnot isinstance(el,...View answers

Questions : 12 :: Making a flat list out of list of lists in Python [duplicate]

$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]'10000 loops, best of 3: 143 usec per loop$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7],...View answers

Questions : 13 :: How to clone or copy a list in Python?

You can slice it: new_list = old_list[:] Alex Martelli's opinion (at least back in 2007) about this is, that it is a weird syntax and it does not make sense to use it ever. ;) (In his opinion,...View answers

Questions : 14 :: What does `if __name__ == "__main__":` do?

Expanding a bit on Harley's answer... When the Python interpreter reads a source file, it executes all of the code found in it. Before executing the code, it will define a few special variables....View answers

Questions : 15 :: What is a metaclass in Python?

A metaclass is the class of a class. Like a class defines how an instance of the class behaves, a metaclass defines how a class behaves. A class is an instance of a metaclass. While in Python you...View answers

Questions : 16 :: Flattening a shallow list in Python

accepted If you're just looking to iterate over a flattened version of the data structure and don't need an indexable sequence, consider itertools.chain and company. >>>...View answers

Questions : 17 :: What is the purpose of self in Python?

The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method...View answers

Questions : 18 :: What does ** (double star) and * (star) do for Python parameters?

The *args and **kwargs is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation. The *args will give...View answers

Questions : 19 :: Is there any way to kill a Thread in Python?

The nice way of handling this if you can afford it (if you are managing your own threads) is to have an exit_request flag that each threads checks on regular interval to see if it is time for him to...View answers

Questions : 20 :: What is the most "pythonic" way to iterate over a list in chunks?

Modified from the recipes section of Python's itertools docs: def grouper(iterable, n, fillvalue=None): args =[iter(iterable)]* n return izip_longest(*args, fillvalue=fillvalue) Example...View answers

Questions : 21 :: How do I avoid having Python class data shared among instances?

38 down vote accepted You want this: class a:def __init__(self): self.list =[] Declaring the variables inside the class declaration makes them "class" members and not...View answers

Questions : 22 :: How do I do variable variables in Python?

down vote accepted Use dictionaries to accomplish this. Dictionaries are stores of keys and values. >>> dct ={'x':1,'y':2,'z':3}>>>...View answers

Questions : 23 :: Python's "is" operator behaves unexpectedly with integers

Take a look at this: >>> a =256>>> b =256>>> id(a)9987148>>> id(b)9987148>>> a =257>>> b =257>>> id(a)11662816>>>...View answers

Questions : 24 :: Does Python have a ternary conditional operator?

Yes, it was added in version 2.5. The syntax is: a if test else b First test is evaluated, then either a or b is returned based on the Boolean value of test; if test evaluates to True a is...View answers

Questions : 25 :: Loop "Forgets" to Remove Some Items

You're modifying the list you're iterating over, which is bound to result in some unintuitive behavior. Instead, make a copy of the list so you don't remove elements from what you're iterating...View answers

Questions : 26 :: Difference between __str__ and __repr__ in Python

Alex summarized well but, surprisingly, was too succinct. First, let me reiterate the main points in Alex’s post: The default implementation is useless (it’s hard to think of one...View answers

Questions : 27 :: What is the difference between old style and new style classes in Python?

Up to Python 2.1, old-style classes were the only flavour available to the user. The concept of (old-style) class is unrelated to the concept of type: if x is an instance of an old-style class,...View answers

Questions : 28 :: Remove items from a list while iterating in Python

somelist =[x for x in somelist if determine(x)] EDIT: Jobs' comment says that he wants the 'determine' to say what should be deleted. That would then be...View answers

Questions : 29 :: Disable output buffering

From Magnus Lycka answer on a mailing list: You can skip buffering for a whole python process using "python -u" (or#!/usr/bin/env python -u etc) or by setting the environment variable...View answers

Questions : 30 :: Non-blocking read on a subprocess.PIPE in python

import sysfrom subprocess import PIPE, Popenfrom threading  import Threadtry:    from Queue import Queue, Emptyexcept ImportError:    from queue import Queue,...View answers

Questions : 31 :: How do I protect Python code?

Usually in cases like this, you have to make a tradeoff. How important is it really to protect the code? Are there real secrets in there (such as a key for symmetric encryption of bank transfers), or...View answers

Questions : 32 :: Fastest way to list all primes below N

Below is a script which compares a number of...View answers

Questions : 33 :: Python, Unicode, and the Windows console

Here's a code excerpt from that page: $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout);...View answers

Questions : 34 :: Understanding Python super() with __init__() methods

accepted super() lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inheritance, where all sorts of fun stuff can...View answers

Questions : 35 :: How do you remove duplicates from a list in Python whilst preserving order?

down vote accepted Here you have some alternatives: Fastest one: def f7(seq): seen = set() seen_add = seen.add return[...View answers

Questions : 36 :: How can I represent an 'Enum' in Python?

from enum import EnumAnimal = Enum('Animal', 'ant bee cat dog')

Questions : 37 :: how can I force division to be floating point in Python?

>>> from __future__ import division>>> a = 4>>> b = 6>>> c = a / b>>> c0.66666666666666663

Questions : 38 :: How to improve performance of this code?

I've been tripped up by this before too. The bottleneck here is actually if neighbor in closedlist. The in statement is so easy to use, you forget that it's linear search, and when you're doing...View answers

Questions : 39 :: How can you profile a Python script?

accepted Python includes a profiler called cProfile. It not only gives the total running time, but also times each function separately, and tells you how many times each function was...View answers

Questions : 40 :: How to generate all permutations of a list in Python

If you're using an older Python (<2.6) for some reason or are just curious to know how it works, here's one nice approach, taken from def...View answers

Questions : 41 :: Python read a single character from the user

class _Getch:    """Gets a single character from standard input.  Does not echo to thescreen."""    def...View answers

Questions : 42 :: Does Python have a built in function for string natural sort?

>>> import natsort>>> x = ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']>>> natsort.natsorted(x, key=lambda y: y.lower())['elm0',...View answers

Questions : 43 :: Local variables in Python nested functions

The nested function looks up variables from the parent scope when executed, not when defined. The function body is compiled, and the 'free' variables (not defined in the function itself by...View answers

Questions : 44 :: Is Using eval In Python A Bad Practice?

Yes, using eval is a bad practice. Just to name a few reasons: There is almost always a better way to do it Very dangerous and insecure Makes debugging difficult Slow In your case you can...View answers

Questions : 45 :: *args and **kwargs? [duplicate]

>>> def print_everything(*args):        for count, thing in enumerate(args):...         print '{0}....View answers

Questions : 46 :: Which Python memory profiler is recommended? [closed]

down vote accepted Heapy is quite simple to use. At some point in your code, you have to write the following: from guppy import hpy h = hpy()print h.heap() This gives you some...View answers

Questions : 47 :: Python List Comprehension Vs. Map

$ python -mtimeit -s'xs=range(10)' 'map(hex, xs)'100000 loops, best of 3: 4.86 usec per loop$ python -mtimeit -s'xs=range(10)' '[hex(x) for x in xs]'100000 loops, best of 3: 5.58 usec per...View answers

Questions : 48 :: How does Python compare string and int?

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their...View answers

Questions : 49 :: How to do relative imports in Python?

everyone seems to want to tell you what you should be doing rather than just answering the question. The problem is that you're running the module as '__main__' by passing the as an...View answers

Questions : 50 :: list comprehension without [ ], Python

>>>''.join( str(_)for _ in xrange(10)) This is called a generator expression, and is explained in PEP 289. The main difference between generator expressions and list comprehensions is...View answers

Questions : 51 :: How can you dynamically create variables in Python via a while loop?

accepted Unless there is an overwhelming need to create a mess of variable names, I would just use a dictionary, where you can dynamically create the key names and associate a value to...View answers

Questions : 52 :: Python string formatting: % vs. .format

To answer your first question... .format just seems more sophisticated in many ways. You can do stuff like re-use arguments, which you can't do with %. An annoying thing about % is also how it can...View answers

Questions : 53 :: Why is the order in Python dictionaries and sets arbitrary?

The order is not arbitrary, but depends on the insertion and deletion history of the dictionary or set, as well as on the specific Python implementation. For the remainder of this answer, for...View answers

Questions : 54 :: What do (lambda) function closures capture in Python?

Scoping in Python is dynamic and lexical. A closure will always remember the name and scope of the variable, not the object it's pointing to. Since all the functions in your example are created in...View answers

Questions : 55 :: Calling a function of a module from a string with the function's name in Python

Assuming module foo with method bar: import foo methodToCall = getattr(foo,'bar') result = methodToCall() As far as that goes, lines 2 and 3 can be compressed to: result =...View answers

Questions : 56 :: How do I parse XML in Python?

accepted I suggest ElementTree. There are other compatible implementations of the same API, such as lxml, and cElementTree in the Python standard library itself; but, in this context,...View answers

Questions : 57 :: Import a module from a relative path

Assuming that both your directories are real python packages (do have the file inside them), here is a safe solution for inclusion of modules relatively to the location of the script. I...View answers

Questions : 58 :: Dynamic module import in Python

Nope, that's pretty much how to do it. You can use exec if you want to as well. Note you can import a list of modules by doing this: >>> moduleNames...View answers

Questions : 59 :: How do I watch a file for changes using Python?

Have you already looked at the documentation available on If you only need it to work under Windows the 2nd example...View answers

Questions : 60 :: Get the cartesian product of a series of lists in Python

import itertoolsfor element in itertools.product(*somelists):    print element

Questions : 61 :: Adding a Method to an Existing Object

In Python, there is a difference between functions and bound methods. >>>def foo():...print"foo"...>>>class A:...def bar( self ):...print"bar"...>>> a =...View answers

Questions : 62 :: Use different Python version with virtualenv

virtualenv -p /usr/bin/python2.6 <path/to/new/virtualenv/>

Questions : 63 :: How do I download a file over HTTP using Python?

import urllib2 response = urllib2.urlopen('') html = This is the most basic way to use the library, minus any error handling. You can also do more complex...View answers

Questions : 64 :: How to import a module given the full path?

There are equivalent convenience functions for compiled Python files and DLLs. For Python 3.3+ this is a bit more involved, unfortunately: import importlib.machinery loader =...View answers

Questions : 65 :: Rolling or sliding window iterator in Python

from itertools import islicedef window(seq, n=2):    "Returns a sliding window (of width n) over data from the iterable"    "   s -> (s0,s1,...s[n-1]),...View answers

Questions : 66 :: How can I merge two Python dictionaries in a single expression?

Say you have two dicts and you want to merge them into a new dict without altering the original dicts: x ={'a':1,'b':2} y ={'b':3,'c':4} y will come second and its values will replace x's...View answers

Questions : 67 :: What kinds of patterns could I enforce on the code to make it easier to translate to another programming language?

I've been building tools (DMS Software Reengineering Toolkit) to do general purpose program manipulation (with language translation being a special case) since 1995, supported by a strong team of...View answers

Questions : 68 :: How to reload a Python module?

import foowhile True:    # Do some things.    if is_changed(foo):        foo = reload(foo)

Questions : 69 :: What's the difference between list and tuples?

Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while...View answers

Questions : 70 :: How to terminate a python subprocess launched with shell=True

import osimport signalimport subprocess# The os.setsid() is passed in the argument preexec_fn so# it's run after the fork() and before  exec() to run the = subprocess.Popen(cmd,...View answers

Questions : 71 :: How does global value mutation used for thread-safety?

The global interpreter lock is used to allow the running of the thread one at a time. This is internal to the program only and used to distribute the functionality along all the virtual machines that...View answers

Questions : 72 :: Write a program to read and write the binary data using python?

The module that is used to write and read the binary data is known as struct. This module allows the functionality and with it many functionalities to be used that consists of the string class. This...View answers

Questions : 73 :: What is the process to run sub-process with pipes that connect both input and output?

The popen2() module is used to run the sub-process but due to some difficulty in processing like creation of deadlock that keep a process blocked that wait for the output from the child and child is...View answers

Questions : 74 :: What are the different ways to generate random numbers?

Random module is the standard module that is used to generate the random number. The method is defined as: import random random.random() The statement random.random() method return the floating...View answers

Questions : 75 :: Write a program to show the singleton pattern used in python.

Singleton patter is used to provide a mechanism that limits the number of instances that can be used by one class. It also allows the same object to be shared between many different parts of the...View answers

Questions : 76 :: How is "self" explicitly defined in a method?

“Self” is a reference variable and an instance attribute that is used instead of the local variable inside the class. The function or the variable of the self like self.x or self.meth()...View answers

Questions : 77 :: What is the use of join() for a string rather than list or tuple method?

The functions and the methods that are used for the functionality uses the string module. This string module is represented as by using the join function in it: ", ".join(['1', '2', '4',...View answers

Questions : 78 :: What is the process of compilation and linking in python?

The compiling and linking allows the new extensions to be compiled properly without any error and the linking can be done only when it passes the compiled procedure. If the dynamic loading is used...View answers

Questions : 79 :: What is the procedure to extract values from the object used in python?

To extract the value it requires the object type to be defined and according to the object type only the values will be fetched. The values will be extracted as: • If the object is a tuple then...View answers

Questions : 80 :: What are the steps required to make a script executable on Unix?

The steps that are required to make a script executable are to: • First create a script file and write the code that has to be executed in it. • Make the file mode as executable by making...View answers

Questions : 81 :: How the string does get converted to a number?

To convert the string into a number the built-in functions are used like int() constructor. It is a data type that is used like int (‘1’) ==1. • float() is also used to show the...View answers

Questions : 82 :: What is the function of negative index?

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...View answers

Questions : 83 :: Write a program to check whether the object is of a class or its subclass.

There is a method which is built-in to show the instances of an object that consists of many classes by providing a tuple in a table instead of individual classes. The method is given as...View answers

Questions : 84 :: Why does delegation performed in Python?

Delegation is a technique that is used in object oriented programming. This is used to show the object and the behavior of the methods that are used. The class can be created to provide an...View answers

Questions : 85 :: What is the function of "self"?

“Self” is a variable that represent the instance of the object to itself. In most of the object oriented programming language, this is passed as to the methods as a hidden parameters that...View answers

Questions : 86 :: What are the ways to write a function using call by reference?

Arguments in python are passed as an assignment. This assignment creates an object that has no relationship between an argument name in source and target. The procedure to write the function using...View answers

Questions : 87 :: What are the commands that are used to copy an object in Python?

The command that is used to copy an object in python includes: • copy.copy() function: This makes a copy of the file from source to destination. It returns a shallow copy of the parameter that...View answers

Questions : 88 :: What is the difference between deep and shallow copy?

Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Whereas, deep copy is used to store the values that are already copied. •...View answers

Questions : 89 :: Write a program to find out the name of an object in python.

The object doesn’t have any name and there is no way the can be found out for objects. The assignment is used to bind a name to the value that includes the name of the object that has to be...View answers

Questions : 90 :: How can the ternary operators be used in python?

The ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it. The operator will be...View answers

Questions : 91 :: Explain the disadvantages of python.

Disadvantages of Python are: Python isn't the best for memory intensive tasks. Python is interpreted language & is slow compared to C/C++ or java. Python not a great choice for a...View answers
More Question

Ask your interview questions on Python

Write Your comment or Questions if you want the answers on Python from Python Experts
Name* :
Email Id* :
Mob no* :
Comment* :

--------- Tutorials ---