Python Interview Questions and Answers

Ratings:
(4)
Views:0
Banner-Img
  • Share this blog:

Python Interview Questions

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

Ans: 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.

Q2) Is there an equivalent of C's "?:" ternary operator?

Ans: No.

Q3) How do I convert a number to a string?

Ans: To convert, e.g., the number 144 to the string '144', use the built-in function str(). If you want 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.

Q4) How do I modify a string in place?

Ans: 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!") >>>''.join(a) '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'

Q5) How do I use strings to call functions/methods?

Ans: 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(): pass

def b(): pass

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) f()

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

def myFunc(): print "hello"

fname = "myFunc"

f = locals()[fname] f()

f = eval(fname) f()

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.

Q6) How do I convert between tuples and lists?

Ans: 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.

Q7) What's a negative index?

Ans: 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.

Inclined to build a profession as Python Developer? Then here is the blog post on, explore Python Training

Q6) How do you remove duplicates from a list?

Ans: 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: List.sort() 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()

Q7) How do you make an array in Python?

Ans: 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.

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

Ans: 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)

Q9) What is self?

Ans: 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).

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

Ans: 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.

 

Python Tutorials

 

Q11) How can I organize my code to make it easier to change the base class?

Ans: 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 = <real base class> class Derived(BaseAlias): def meth(self): BaseAlias.meth(self)

Q12) Where is the math.py (socket.py, regex.py, etc.) source file?

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

modules are written in Python (.py);

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

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

print sys.builtin_module_names

For in-depth knowledge on Python, click on below

You liked the article?

Like : 0

Vote for difficulty

Current difficulty (Avg): Medium

Recommended Courses

1/15

About Author
Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.


Stay Updated


Get stories of change makers and innovators from the startup ecosystem in your inbox