Python Interview Questions and Answers

Prepare Python interview questions for freshers and experienced candidates. This page includes important questions, answer previews, preparation guidance, related interview topics and cached content for faster page loading.

🐍
103+ Python questions available

About Python Interview Preparation

Python interview questions and answers for freshers and experienced candidates, including basic concepts, advanced topics, practical examples, project discussion points and common HR preparation guidance.

For better preparation, read each question carefully, understand the concept, prepare one real example, and connect your answer with your project or work experience.

Python Questions List

Quick list of important Python interview questions. Detailed answer previews are available below.

  1. what is Python's slice notation?
  2. What is Python? State some programming language features of Python.
  3. Explain how python is interpreted.
  4. What are the rules for local and global variables in Python?
  5. How do I test one variable against multiple values?
  6. How do you split a list into evenly sized chunks in Python?
  7. Python list of lists, changes reflected across sublists unexpectedly
  8. How do I pass a variable by reference?
  9. What does the yield keyword do in Python?
  10. Calling an external command in Python
  11. Flatten (an irregular) list of lists in Python
  12. Making a flat list out of list of lists in Python [duplicate]
  13. How to clone or copy a list in Python?
  14. What does `if __name__ == "__main__":` do?
  15. What is a metaclass in Python?
  16. Flattening a shallow list in Python
  17. What is the purpose of self in Python?
  18. What does ** (double star) and * (star) do for Python parameters?
  19. Is there any way to kill a Thread in Python?
  20. What is the most "pythonic" way to iterate over a list in chunks?
  21. How do I avoid having Python class data shared among instances?
  22. How do I do variable variables in Python?
  23. Python's "is" operator behaves unexpectedly with integers
  24. Does Python have a ternary conditional operator?
  25. Loop "Forgets" to Remove Some Items
  26. Difference between __str__ and __repr__ in Python
  27. What is the difference between old style and new style classes in Python?
  28. Remove items from a list while iterating in Python
  29. Disable output buffering
  30. Non-blocking read on a subprocess.PIPE in python

Question 1: what is Python's slice notation?

Answer: 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 necessary to be familiar with.Important DefinitionsTo begin with, let's define a few terms:    start: the beginning index of the slice, it will include the element at this index unless it is the same as stop, defaults to 0, i.e. the first index. If it's negative, it means to start n items from the end.    stop: the ending index of the slice, it does not include the element at this index, defaults to length of the sequence be...

View detailed answer →

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

Answer: 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 van Rossum Salient features of Python are -Simple & Easy: Python is simple language & easy to learn. -Free/open source: it means everybody can use python without purchasing license. -High level language: when coding in Python one need not worry about low-level details. -Portable: Python codes are Machine & platform independent. -Extensible: Python program supports usage of C/ C++ codes. -Embeddable Language: Python code can be embedded within C/C...

View detailed answer →

Question 3: Explain how python is interpreted.

Answer: 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 again translated it into the native language / machine language that is executed. So Python is an Interpreted language.

View detailed answer →

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

Answer: 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 define it as global. Variable referenced inside the function are implicit global. Following code snippet will explain further the difference #!/usr/bin/python # Filename: variable_localglobal.py def fun1(a):             print 'a:', a             a= 33;             print 'local a: ', a a =...

View detailed answer →

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

Answer: 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 ==1or y ==1or z ==1: x and y are otherwise evaluated on their own (False if 0, True otherwise). You can shorten that to: if1in(x, y, z): or better still: if1in{x, y, z}: using a set to take advantage of the constant-cost membership test (in takes a fixed amount of time whatever the left-hand operand is). When you use or, python sees each side of the operator as separate expressions. The expression x or y == 1 is treated as first a boolean test for x, the...

View detailed answer →

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

Answer: 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 pprint pprint.pprint(list(chunks(range(10,75),10)))[[10,11,12,13,14,15,16,17,18,19],[20,21,22,23,24,25,26,27,28,29],[30,31,32,33,34,35,36,37,38,39],[40,41,42,43,44,45,46,47,48,49],[50,51,52,53,54,55,56,57,58,59],[60,61,62,63,64,65,66,67,68,69],[70,71,72,73,74]]

View detailed answer →

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

Answer: 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 that you create a new list at each position. One way to do it is [[1]*4for n in range(3)]

View detailed answer →

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

Answer: 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 mutable, but others aren't So: If you pass a mutable object into a method, the method gets a reference to that same object and you can mutate it to your heart's delight, but if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object. If you pass an immutable object to a method, you still can't rebind the outer reference, and you can't even mut...

View detailed answer →

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

Answer: 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 iteration: >>> mylist =[1,2,3]>>>for i in mylist:...print(i)123

View detailed answer →

Question 10: Calling an external command in Python

Answer: 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, the "real" status code, better error handling, etc...). I think os.system is deprecated, too, or will be:

View detailed answer →

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

Answer: 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, basestring):for sub in flatten(el):yield sub else:yield el

View detailed answer →

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

Answer: $ 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], [8,9]]*99' 'sum(l, [])'1000 loops, best of 3: 969 usec per loop$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,l)'1000 loops, best of 3: 1.1 msec per loop

View detailed answer →

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

Answer: 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, the next one is more readable).

View detailed answer →

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

Answer: 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. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module's name. In the case of your script, let's assume that it's executing as the main function, e.g. you said something like python threading_example.py

View detailed answer →

Question 15: What is a metaclass in Python?

Answer: 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 can use arbitrary callables for metaclasses (like Jerub shows), the more useful approach is actually to make it an actual class itself. 'type' is the usual metaclass in Python. In case you're wondering, yes, 'type' is itself a class, and it is its own type. You won't be able to recreate something like 'type' purely in Python, but Python cheats a little. To create your own metaclass in Python you really just want to subclass 'type'. A metaclass is mos...

View detailed answer →

Question 16: Flattening a shallow list in Python

Answer: 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. >>> list_of_menuitems =[['image00','image01'],['image10'],[]]>>>import itertools >>> chain = itertools.chain(*list_of_menuitems)>>>print(list(chain))['image00','image01','image10']

View detailed answer →

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

Answer: 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 belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on. That makes methods entirely the same as functions, and leaves the actual name to use up to you (although self is the convention, and people will generally frown at you when you use something else.) self is not special to the code, it's just another object. Python could have done something else to distinguish normal name...

View detailed answer →

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

Answer: 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 you all function parameters as a tuple: In[1]:def foo(*args):...:for a in args:...:print a ...:...:In[2]: foo(1)1In[4]: foo(1,2,3)123

View detailed answer →

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

Answer: 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 exit. For example: import threading classStoppableThread(threading.Thread):"""Thread class with a stop() method. The thread itself has to check regularly for the stopped() condition."""def __init__(self): super(StoppableThread, self).__init__() self._stop = threading.Event()def stop(self): self._stop.set()def stopped(self):return self._stop.isSet()

View detailed answer →

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

Answer: 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 In pseudocode to keep the example terse. grouper('ABCDEFG',3,'x')-->'ABC''DEF''Gxx'

View detailed answer →

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

Answer: 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 instance members. Declaring them inside the __init__ method makes sure that a new instance of the members is created alongside every new instance of the object, which is the behavior you're looking for.

View detailed answer →

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

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

View detailed answer →

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

Answer: Take a look at this: >>> a =256>>> b =256>>> id(a)9987148>>> id(b)9987148>>> a =257>>> b =257>>> id(a)11662816>>> id(b)11662828

View detailed answer →

Question 24: Does Python have a ternary conditional operator?

Answer: 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 returned, else b is returned. For example: >>>'true'ifTrueelse'false''true'>>>'true'ifFalseelse'false''false' Keep in mind that it's frowned upon by some Pythonistas for: The order of the arguments is different from many other languages (such as C, Ruby, Java, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour (they may reverse the order). Some find it "unwieldy", since it goes against the flow of tho...

View detailed answer →

Question 25: Loop "Forgets" to Remove Some Items

Answer: 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 through. for char in textlist[:]:#shallow copy of the list# etc To clarify the behavior you're seeing, check this out. Put print char, textlist at the beginning of your (original) loop. You'd expect, perhaps, that this would print out your string vertically, alongside the list, but what you'll actually get is this: H ['H','e','y',' ','l','o','o','k',' ','W','o','r','d','s','!'] e ['H','e','y',' ','l','o','o','k',' ','W','o','r','d','s','!']['H','y',' ',...

View detailed answer →

Question 26: Difference between __str__ and __repr__ in Python

Answer: 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 which wouldn’t be, but yeah) __repr__ goal is to be unambiguous __str__ goal is to be readable Container’s __str__ uses contained objects’ __repr__

View detailed answer →

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

Answer: 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, then x.__class__ designates the class of x, but type(x) is always <type 'instance'>. This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called instance. New-style classes were introduced in Python 2.2 to unify classes and types. A new-style class neither more nor less than a user-defined type. If x is an instance of a new-style class, then type(x) is the same as x.__clas...

View detailed answer →

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

Answer: 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 just.

View detailed answer →

Question 29: Disable output buffering

Answer: 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 PYTHONUNBUFFERED. You could also replace sys.stdout with some other stream like wrapper which does a flush after every call. classUnbuffered(object):def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush()def __getattr__(self, attr):return getattr(self.stream, attr)import sys sys.stdout =Unbuffered(sys.stdout)print'Hello'

View detailed answer →

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

Answer: import sysfrom subprocess import PIPE, Popenfrom threading  import Threadtry:    from Queue import Queue, Emptyexcept ImportError:    from queue import Queue, Empty  # python 3.xON_POSIX = 'posix' in sys.builtin_module_namesdef enqueue_output(out, queue):    for line in iter(out.readline, b''):        queue.put(line)    out.close()p = Popen(['myprogram.exe'], stdout=PIPE, bufsize=1, close_fds=ON_POSIX)q = Queue()t = Thread(target=enqueue_output, args=(p.stdout, q))t.daemon = True # thread dies with the programt.start()# ... do other things...

View detailed answer →

Question 31: How do I protect Python code?

Answer: 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 are you just being paranoid? Choose the language that lets you develop the best product quickest, and be realistic about how valuable your novel ideas are.

View detailed answer →

Question 32: Fastest way to list all primes below N

Answer: Below is a script which compares a number of implementations: ambi_sieve_plain, rwh_primes, rwh_primes1, rwh_primes2, sieveOfAtkin, sieveOfEratosthenes, sundaram3, sieve_wheel_30, ambi_sieve (requires numpy) primesfrom3to (requires numpy) primesfrom2to (requires numpy) Many thanks to stephan for bringing sieve_wheel_30 to my attention. Credit goes to Robert William Hanks for primesfrom2to, primesfrom3to, rwh_primes, rwh_primes1, and rwh_primes2. Of the plain Python methods tested, with psyco, for n=1000000, rwh_primes1 was the fastest tested.

View detailed answer →

Question 33: Python, Unicode, and the Windows console

Answer: 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); line = u"u0411n"; print type(line), len(line); sys.stdout.write(line); print line' UTF-8<type 'unicode'>2ББ $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); line = u"u0411n"; print type(line), len(line); sys.stdout.write(line); print line'| cat None<type 'unicode'>2ББ

View detailed answer →

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

Answer: 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 happen. See the standard docs on super if you haven't already. Note that the syntax changed in Python 3.0: you can just say super().__init__() instead of super(ChildB, self).__init__() which IMO is quite a bit nicer.

View detailed answer →

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

Answer: down vote accepted Here you have some alternatives: http://www.peterbe.com/plog/uniqifiers-benchmark Fastest one: def f7(seq): seen = set() seen_add = seen.add return[ x for x in seq ifnot(x in seen or seen_add(x))]

View detailed answer →

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

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

View detailed answer →

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

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

View detailed answer →

Question 38: How to improve performance of this code?

Answer: 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 linear searches on lists, it can add up fast. What you can do is convert closedlist into a set object. This keeps hashes of its items so the in operator is much more efficient than for lists. However, lists aren't hashable items, so you will have to change your configurations into tuples instead of lists. If the order of closedlist is crucial to the algorithm, you could use a set for the in operator and keep an parallel list around for your results. I ...

View detailed answer →

Question 39: How can you profile a Python script?

Answer: 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 called, making it easy to determine where you should make optimizations. You can call it from within your code, or from the interpreter, like this: import cProfile cProfile.run('foo()')

View detailed answer →

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

Answer: 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 http://code.activestate.com/recipes/252178/: def all_perms(elements):if len(elements)<=1:yield elements else:for perm in all_perms(elements[1:]):for i in range(len(elements)):# nb elements[0:1] works in both string and list contextsyield perm[:i]+ elements[0:1]+ perm[i:]

View detailed answer →

Question 41: Python read a single character from the user

Answer: class _Getch:    """Gets a single character from standard input.  Does not echo to thescreen."""    def __init__(self):        try:            self.impl = _GetchWindows()        except ImportError:            self.impl = _GetchUnix()    def __call__(self): return self.impl()class _GetchUnix:    def __init__(self):        import tty, sys    def __call__(...

View detailed answer →

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

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

View detailed answer →

Question 43: Local variables in Python nested functions

Answer: 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 assignment), are verified, then bound as closure cells to the function, with the code using an index to reference each cell. pet_function thus has one free variable (cage) which is then referenced via a closure cell, index 0. The closure itself points to the local variable cage in the get_petters function. When you actually call the function, that closure is then used to look at the value of cage in the surrounding scope at the time you call the function. H...

View detailed answer →

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

Answer: 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 use setattr instead: classSong:"""The class to store the details of each song""" attsToStore=('Name','Artist','Album','Genre','Location')def __init__(self):for att in self.attsToStore: setattr(self, att.lower(),None)def setDetail(self, key, val):if key in self.attsToStore: setattr(self, key.lower(), val)

View detailed answer →

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

Answer: >>> def print_everything(*args):        for count, thing in enumerate(args):...         print '{0}. {1}'.format(count, thing)...>>> print_everything('apple', 'banana', 'cabbage')0. apple1. banana2. cabbage

View detailed answer →

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

Answer: 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 output like this: Partition of a set of 132527 objects.Total size =8301532 bytes.IndexCount%Size%Cumulative%Kind(class/ dict of class)03514427214041226214041226 str 13839729130902016344943242 tuple 253007398569418928850 dict (no owner)

View detailed answer →

Question 47: Python List Comprehension Vs. Map

Answer: $ 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 loop

View detailed answer →

Question 48: How does Python compare string and int?

Answer: 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 address. When you order two strings or two numeric types the ordering is done in the expected way (lexicographic ordering for string, numeric ordering for integers). When you order a numeric and a non-numeric type, the numeric type comes first. >>>5<'foo'True>>>5<(1,2)True>>>5<{}True>>>5<[1,2]True

View detailed answer →

Question 49: How to do relative imports in Python?

Answer: 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 mod1.py as an argument to the interpreter. From PEP 328: Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system. In Python 2.6, they're adding the ability to reference modules ...

View detailed answer →

Question 50: list comprehension without [ ], Python

Answer: >>>''.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 that the former don't create the list in memory. Note that there's a third way to write the expression: ''.join(map(str, xrange(10)))

View detailed answer →

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

Answer: 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 each. a ={} k =0while k <10:<dynamically create key> key =...<calculate value> value =... a[key]= value k +=1 There are also some interesting data structures in the new 'collections' module that might be applicable:

View detailed answer →

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

Answer: 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 either take a variable or a tuple. You'd think the following would always work: "hi there %s"% name yet, if name happens to be (1, 2, 3), it will throw a TypeError. To guarantee that it always prints, you'd need to do "hi there %s"%(name,)# supply the single argument as a single-item tuple which is just ugly. .format doesn't have those issues. Also in the second example you gave, the .format example is much cleaner looking

View detailed answer →

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

Answer: 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 'dictionary', you can also read 'set'; sets are implemented as dictionaries with just keys and no values. Keys are hashed, and hash values are assigned to slots in a dynamic table (it can grow or shrink based on needs). And that mapping process can lead to collisions, meaning that a key will have to be slotted in a next slot based on what is already there. Listing the contents loops over the slots, and so keys are listed in the order they currently resid...

View detailed answer →

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

Answer: 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 the same scope and use the same variable name, they always refer to the same variable.

View detailed answer →

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

Answer: 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 = getattr(foo,'bar')() if that makes more sense for your use case. You can use getattr in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.

View detailed answer →

Question 56: How do I parse XML in Python?

Answer: 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, what they chiefly add is even more speed -- the ease of programming part depends on the API, which ElementTree defines. After building an Element instance e from the XML, e.g. with the XML function, or by parsing a file with something like e = xml.etree.ElementTree.parse('thefile.xml').getroot() or any of the many other ways shown at ElementTree, you just do something like: for atype in e.findall('type'):print(atype.get('foobar')) and similar, usually pretty sim...

View detailed answer →

Question 57: Import a module from a relative path

Answer: Assuming that both your directories are real python packages (do have the __init__.py file inside them), here is a safe solution for inclusion of modules relatively to the location of the script. I assume that you want to do this because you need to include a set of modules with your script. I use this in production in several products and works in many special scenarios like: scripts called from another directory or executed with python execute instead of opening a new interpreter.

View detailed answer →

Question 58: Dynamic module import in Python

Answer: 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 =['sys','os','re','unittest']>>> moduleNames ['sys','os','re','unittest']>>> modules = map(__import__, moduleNames)

View detailed answer →

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

Answer: Have you already looked at the documentation available on http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html? If you only need it to work under Windows the 2nd example seems to be exactly what you want (if you exchange the path of the directory with the one of the file you want to watch). Otherwise, polling will probably be the only really platform-independent option.

View detailed answer →

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

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

View detailed answer →

Question 61: Adding a Method to an Existing Object

Answer: In Python, there is a difference between functions and bound methods. >>>def foo():...print"foo"...>>>class A:...def bar( self ):...print"bar"...>>> a = A()>>> foo <function foo at 0x00A98D70>>>> a.bar <bound method A.bar of <__main__.A instance at 0x00A9BC88>>>>>

View detailed answer →

Question 62: Use different Python version with virtualenv

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

View detailed answer →

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

Answer: import urllib2 response = urllib2.urlopen('http://www.example.com/') html = response.read() This is the most basic way to use the library, minus any error handling. You can also do more complex stuff such as changing headers. The documentation can be found here.

View detailed answer →

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

Answer: 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 = importlib.machinery.SourceFileLoader("module.name","/path/to/file.py") foo = loader.load_module() foo.MyClass()

View detailed answer →

Question 65: Rolling or sliding window iterator in Python

Answer: 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]), (s1,s2,...,sn), ...                   "    it = iter(seq)    result = tuple(islice(it, n))    if len(result) == n:        yield result        for elem in it:        result = result[1:] + (elem,)    &n...

View detailed answer →

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

Answer: 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 values, thus 'b' will point to 3 in our final result.

View detailed answer →

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

Answer: 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 computer scientists. DMS provides generic parsing, AST building, symbol tables, control and data flow analysis, application of translation rules, regeneration of source text with comments, etc., all parameterized by explicit definitions of computer languages. The amount of machinery you need to do this well is vast (especially if you want to be able to do this for multiple languages in a general way), and then you need reliable parsers for languages ...

View detailed answer →

Question 68: How to reload a Python module?

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

View detailed answer →

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

Answer: 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 lists are homogeneous sequences. Tuples have structure, lists have order. Using this distinction makes code more explicit and understandable. One example would be pairs of page and line number to reference locations in a book, e.g.: my_location =(42,11)# page number, line number You can then use this as a key in a dictionary to store notes on locations. A list on the other hand could be used to store multiple locations. Naturally one might want to ad...

View detailed answer →

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

Answer: 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 shell.pro = subprocess.Popen(cmd, stdout=subprocess.PIPE,                        shell=True, preexec_fn=os.setsid) os.killpg(pro.pid, signal.SIGTERM)  # Send the signal to all the process groups

View detailed answer →

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

Answer: 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 are used. Python allows the switching between the threads to be performed by using the byte code instructions that are used to provide platform-independence. The sys.setcheckinterval() method is used that allow the switching to occur during the implementation of the program and the instruction. This provides the understanding in the field of accounting to use the byte code implementation that makes it portable to use. The atomicity can be provide...

View detailed answer →

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

Answer: 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 class contains the binary data that is in the form of numbers that gets converted in python objects for use and vice versa. The program can read or write the binary data is: import struct f = open(file-name, "rb") # This Open() method allows the file to get opened in binary mode to make it portable for # use. s = f.read(8) x, y, z = struct.unpack(">hhl", s) The ‘>” is used to show the format string that allows the string to be co...

View detailed answer →

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

Answer: 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 waiting for the input. The dead lock occurs due to the fact that parent and child doesn’t have the synchronization and both are waiting to get the processor to provide the resources to one another. Use of popen3() method allow the reading of stdout and stderr to take place where the internal buffer increases and there is no read() takes place to share the resources. popen2() take care of the deadlock by providing the methods like wait() and ...

View detailed answer →

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

Answer: 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 point number that is in the range of [0, 1). The function generates the random float numbers. The methods that are used with the random class are the bound methods of the hidden instances. The instances of the Random can be done to show the multi-threading programs that creates different instance of individual threads. The other random generators that are used in this are: • randrange(a, b): it chooses an integer and define the range in-between [a...

View detailed answer →

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

Answer: 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 code. This allows the global variables to be used as the actual data that is used is hidden by the singleton class interface. The singleton class interface can have only one public member and one class method Handle. Private constructors are not used to create an object that is used outside the class. The process waits for the static member function to create new instances and return the singleton object. The code that is used to call the singleton ob...

View detailed answer →

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

Answer: “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() can be used in case the class is not known. There are no variables declared as local. It doesn’t have any syntax and it allow the reference to be passed explicity or call the method for the class that is in use. The use of writebaseclass.methodname(self, <argument list>) shows that the method of _init_() can be extended to the base class methods. This also solves the problem that is syntactic by using the assignment and the local variab...

View detailed answer →

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

Answer: 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', '8', '16']) that results in "1, 2, 4, 8, 16" The string variable that is used provide a fixed string literal to allow the names that are used to be bounded to the strings. join() is a string method that is used to provide a separator string to use the function over the sequence of the string and insert the function to an adjacent elements. The method uses any number of arguments that follow some rules that has to be put up for the sequence objects that the cl...

View detailed answer →

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

Answer: 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 then it depends on the style that is being provided with the system. The python interpreter can be used to provide the dynamic loading of the configuration setup files and will rebuild the interpreter. The steps that is required in this as: • Create a file with any name and in any lanugage that is supported by the compiler of your system. For example comp.c • Place this file in the Modules/ directory of the distribution which is getting us...

View detailed answer →

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

Answer: 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 PyTuple_Size() method is used that returns the length of the values and another method PyTuple_GetItem() returns the data item that is stored at a specific index. • If the object is a list then PyListSize() is having the same function that is defined for the tuple and PyList_GetItem() that also return the data items at a specified index. • Strings uses PyString_Size() to return the length of the value and PyString_AsString() that return ...

View detailed answer →

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

Answer: 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 the first line starts with #! this is the line that python interpreter reads. • Set the permission for the file by using chmod +x file. The file uses the line that is the most important line to be used: #!/usr/local/bin/python • This explains the pathname that is given to the python interpreter and it is independent of the environment programs. • Absolute pathname should be included so that the interpreter can interpret and execute t...

View detailed answer →

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

Answer: 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 number in the format as float(‘1’)=1. • The number by default are interpreted as decimal and if it is represented by int(‘0x1’) then it gives an error as ValueError. In this the int(string,base) function takes the parameter to convert string to number in this the process will be like int(‘0x1’,16)==16. If the base parameter is defined as 0 then it is indicated by an octal and 0x indicates it as hexadecimal numb...

View detailed answer →

Question 82: What is the function of negative index?

Answer: 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 s...

View detailed answer →

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

Answer: 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 isinstance(obj,cls) and in more details given as: isinstance(obj, (class1, class2, ...)) that is used to check about the object’s presence in one of the classes. The built in types can also have many formats of the same function like isinstance(obj, str) or isinstance(obj, (int, long, float, complex)). It is not preferred to use the class instead user-defined classes are made that allow easy object-oriented style to define the behavior of the object&rsq...

View detailed answer →

Question 84: Why does delegation performed in Python?

Answer: 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 implementation of the method that allows the method to be referenced. The delegate is having the parameter and the return value in an object. It also allows the methods to be passed as parameters and allow the defining of the callback methods that can be grouped together in multiple methods. These methods can be called from a single event. The example shows a class that captures the behavior of the file and converts data from lower to uppercase. class upcas...

View detailed answer →

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

Answer: “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 is defined by an object. But, in python it is declare it and pass it explicitly. It is the first argument that gets created in the instance of the class A and the parameters to the methods are passed automatically. It refers to separate instance of the variable for individual objects. This is the first argument that is used in the class instance and the “self” method is defined explicitly to all the methods that are used and present. ...

View detailed answer →

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

Answer: 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 call by reference includes: The tuple result can be returned to the object which called it. The example below shows it: def function(a, b): a = 'value' b = b + 1 # a and b are local variables that are used to assign the new objects return a, b # This is the function that is used to return the value stored in b • The use of global variables allows the function to be called as reference but this is not the safe method to call any function. •...

View detailed answer →

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

Answer: 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 is passed. • copy.deepcopy(): This also creates a copy of the object from source to destination. It returns a deep copy of the parameter that is passed to the function. The dictionary consists of all the objects and the copy() method which is used as: newdict = olddict.copy() The assignment statement doesn’t copy any object but it creates a binding between the target and the object that is used for the mutable items. Copy is required to ...

View detailed answer →

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

Answer: 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. • Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Whereas, deep copy doesn’t copy the reference pointers to the objects. Deep copy makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won...

View detailed answer →

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

Answer: 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 bound by a value. If the value is callable then the statements are made true and then the program followed can be used to find the reference name of an object. class try: pass B = A a = B() b = a print b <__main__.try instance at 0x16D07CC> print b The class consists of name and the names are invoked by using the the variable B that creates an instance for the class try. The method is to find out from all the namespaces that the object exists a...

View detailed answer →

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

Answer: 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 given as: [on_true] if [expression] else [on_false] x, y = 25, 50 big = x if x < y else y This is the lowest priority operator that is used in making a decision that is based on the values of true or false. The expression gets evaluated like if x<y else y, in this case if x<y is true then the value is returned as big=x and if it is incorrect then big=y will be sent as a result. 

View detailed answer →

Question 91: Explain the disadvantages of python.

Answer: 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 high-graphic 3d game that takes up a lot of CPU. Python is evolving continuously, with constant evolution there is little substantial documentation available for the language.

View detailed answer →

Question 92: How is python interpreted language?

Answer: An interpreted language is the programming language which is not machine level coding before runtime. Hence, python is said to be an interpreted programing language.

View detailed answer →

Question 93: What is PEP 8?

Answer: PEP stands for Python Enhancement Proposal. A set of rules that specify how to format Python code for readability is PEP 8.

View detailed answer →

Question 94: How can you generate random numbers in Python?

Answer: We use the random module to generate random numbers. example: import random random.random

View detailed answer →

Question 95: Is Indentation necessary in python? If yes. Why so?

Answer: Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block.

View detailed answer →

Question 96: What are the various built-in types in Python?

Answer: Integer Floating-point Complex number Strings Boolean Built-in functions

View detailed answer →

Question 97: What are decorators in Python?

Answer: Decorators in Python are essentially functions that add functionality to an existing function in python without changing the structure of the function itself.

View detailed answer →

Question 98: How .py is different from .pyc files?

Answer: .py files contain the source code of a program .pyc file contain the bytecode of your program

View detailed answer →

Question 99: What type of language is python? Programming or scripting?

Answer: Python is considered a Scripting language. But in general terms also considered as General purpose language.

View detailed answer →

Question 100: What are the common advantages of using Python?

Answer: Easy to use Dynamically typed Free and Open Source Portable

View detailed answer →

Question 101: What does Lambda functions role in python?

Answer: Lambda function is an anonymous function in python, that can accept any number of arguments, but can only have a single expression.

View detailed answer →

Question 102: One difference between Array and list.

Answer: Data type of array should be homogenous Data type of list can be heterogenous

View detailed answer →

Question 103: Brief on pass keyword in python.

Answer: Pass keyword represents a null operation. When we want to keep a function empty declare it and give a definition. We use the pass in place of defination.

View detailed answer →
Python interview preparation tip: Start with basic definitions, then prepare practical examples, common mistakes, project usage, scenario-based questions and HR discussion points.