Python Interview Questions with Answers Page I


Jump to: navigation, search

Interview Question Home

1. What is Python?

Python is an interpreted, interactive, object-oriented programming language. It incorporates

modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python

combines remarkable power with very clear syntax. It has interfaces to many system calls and

libraries, as well as to various window systems, and is extensible in C or C++. It is also

usable as an extension language for applications that need a programmable interface. Finally,

Python is portable: it runs on many Unix variants, on the Mac, and on PCs under MS-DOS, Windows,

Windows NT, and OS/2.

2. Is there a tool to help find bugs or perform static analysis?


PyChecker is a static analysis tool that finds bugs in Python source code and warns about code

complexity and style. Pylint is another tool that checks if a module satisfies a coding standard,

and also makes it possible to write plug-ins to add a custom feature.

3. What is 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.

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

In Python, variables that are only referenced inside a function are implicitly global. If a variable

is assigned a new value anywhere within the function's body, it's assumed to be a local. If a variable

is ever assigned a new value inside the function, the variable is implicitly local, and you need to

explicitly declare it as 'global'.

Though a bit surprising at first, a moment's consideration explains this. On one hand, requiring global

for assigned variables provides a bar against unintended side-effects. On the other hand, if global was

required for all global references, you'd be using global all the time. You'd have to declare as global

every reference to a builtin function or to a component of an imported module. This clutter would defeat

the usefulness of the global declaration for identifying side-effects.

5. How do I copy an object in Python?

In general, try copy.copy() or copy.deepcopy() for the general case. Not all objects can be copied, but most can.

Some objects can be copied more easily. Dictionaries have a copy() method:

newdict = olddict.copy()

Sequences can be copied by slicing:

new_l = l[:]

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

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

For integers, use the built-in int() type constructor, e.g. int('144') == 144. Similarly, float() converts

to floating-point, e.g. float('144') == 144.0.

By default, these interpret the number as decimal, so that int('0144') == 144 and int('0x144') raises

ValueError. int(string, base) takes the base to convert from as a second optional argument,

so int('0x144', 16) == 324. If the base is specified as 0, the number is interpreted using Python's

rules: a leading '0' indicates octal, and '0x' indicates a hex number.

Do not use the built-in function eval() if all you need is to convert strings to numbers. eval() will be

significantly slower and it presents a security risk: someone could pass you a Python expression that

might have unwanted side effects. For example, someone could pass __import__('os').system("rm -rf $HOME")

which would erase your home directory.

eval() also has the effect of interpreting numbers as Python expressions, so that e.g. eval('09') gives

a syntax error because Python regards numbers starting with '0' as octal (base 8).

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

9. 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 hashable) this is often faster

d = {}

for x in List: d[x]=x

List = d.values()

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

Personal tools