Python Interview Questions

Python Interview Questions And Answers

How can I find the methods or attributes of an object?

For an instance x of a user-defined class, dir(x) returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class.

Is there an equivalent of C’s “?:” ternary operator?


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.

How do I modify a string in place?

You can’t, because strings are immutable. If you need an object with this ability, try converting the string to a list or use the array module:

>>> s = “Hello, world”
>>> a = list(s)
>>>print a
[‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘,’, ‘ ‘, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’]
>>> a[7:] = list(“there!”)
‘Hello, there!’

>>> import array
>>> a = array.array(‘c’, s)
>>> print a
array(‘c’, ‘Hello, world’)
>>> a[0] = ‘y’ ; print a
array(‘c’, ‘yello world’)
>>> a.tostring()
‘yello, world’

How do I use strings to call functions/methods?

There are various techniques.

* The best is to use a dictionary that maps strings to functions. The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct:

def a():

def b():

dispatch = {‘go’: a, ‘stop’: b} # Note lack of parens for funcs

dispatch[get_input()]() # Note trailing parens to call function
Use the built-in function getattr():

import foo
getattr(foo, ‘bar’)()

Note that getattr() works on any object, including classes, class instances, modules, and so on.

This is used in several places in the standard library, like this:

class Foo:
def do_foo(self):

def do_bar(self):

f = getattr(foo_instance, ‘do_’ + opname)

Use locals() or eval() to resolve the function name:

def myFunc():
print “hello”

fname = “myFunc”

f = locals()[fname]

f = eval(fname)

Note: Using eval() is slow and dangerous. If you don’t have absolute control over the contents of the string, someone could pass a string that resulted in an arbitrary function being executed.

How do I convert between tuples and lists?

The function tuple(seq) converts any sequence(actually, any iterable) into a tuple with the same items in the same order.

For example, tuple([1, 2, 3]) yields (1, 2, 3) and tuple(‘abc’) yields (‘a’, ‘b’, ‘c’). If the argument is a tuple, it does not make a copy but returns the same object, so it is cheap to call tuple() when you aren’t sure that an object is already a tuple.

The function list(seq) converts any sequence or iterable into a list with the same items in the same order. For example, list((1, 2, 3)) yields [1, 2, 3] and list(‘abc’) yields [‘a’, ‘b’, ‘c’]. If the argument is a list, it makes a copy just like seq[:] would.

What’s a negative index?

Python sequences are indexed with positive numbers and negative numbers. For positive numbers 0 is the first index 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the penultimate (next to last) index and so forth. Think of seq[-n] as the same as seq[len(seq)-n].

Using negative indices can be very convenient. For example S[:-1] is all of the string except for its last character, which is useful for removing the trailing newline from a string.

Accelerate your career with Python Training and become expertise Python developer.

How do you remove duplicates from a list?

If you don’t mind reordering the list, sort it and then scan from the end of the list, deleting duplicates as you go:

if List:
last = List[-1]
for i in range(len(List)-2, -1, -1):
if last==List[i]: del List[i]
else: last=List[i]

If all elements of the list may be used as dictionary keys (i.e. they are all hash able) this is often faster

d = {}
for x in List: d[x]=x
List = d.values()

How do you make an array in Python?

Use a list:
[“this”, 1, “is”, “an”, “array”]

Lists are equivalent to C or Pascal arrays in their time complexity; the primary difference is that a Python list can contain objects of many different types.

The array module also provides methods for creating arrays of fixed types with compact representations, but they are slower to index than lists. Also note that the Numeric extensions and others define array-like structures with various characteristics as well.

To get Lisp-style linked lists, you can emulate cons cells using tuples:

lisp_list = (“like”, (“this”, (“example”, None) ) )

If mutability is desired, you could use lists instead of tuples. Here the analogue of lisp car is lisp_list[0] and the analogue of cdr is lisp_list[1]. Only do this if you’re sure you really need to, because it’s usually a lot slower than using Python lists.

How do I apply a method to a sequence of objects?

Use a list comprehension:

result = [obj.method() for obj in List]

More generically, you can try the following function:

def method_map(objects, method, arguments):
“””method_map([a,b], “meth”, (1,2)) gives [a.meth(1,2), b.meth(1,2)]”””
nobjects = len(objects)
methods = map(getattr, objects, [method]*nobjects)
return map(apply, methods, [arguments]*nobjects)

What is self?

Self is merely a conventional name for the first argument of a method. A method defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for some instance x of the class in which the definition occurs; the called method will think it is called as meth(x, a, b, c).

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.

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.


BaseAlias = <real base class>
class Derived(BaseAlias):
def meth(self):

Where is the (,, etc.) source file?

There are (at least) three kinds of modules in Python:

 modules written in Python (.py);

 modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);

modules written in C and linked with the interpreter; to get a list of these, type:
import sys

print sys.builtin_module_names

“At TekSlate, we are trying to create high quality tutorials and articles, if you think any information is incorrect or want to add anything to the article, please feel free to get in touch with us at, we will update the article in 24 hours.”

0 Responses on Python Interview Questions"

    Leave a Message

    Your email address will not be published. Required fields are marked *


    Please leave a message and we'll get back to you soon.
    Three + 6