Python interview questions

Top most important Python interview questions and answers by Experts:

Here is a list of Top most important Python interview questions and answers by Experts.If you want to download Python interview questions pdf free ,you can register with RVH techguru. Our experts prepared these Python interview questions to accommodate freshers level to most experienced level technical interviews.

If you want to become an expert in Python ,Register for Python online training here.

 

1) What is Python? What are the benefits of using Python?
Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source.
2) What is PEP 8?
PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable.
3) What is pickling and unpickling?
Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
4) How Python is interpreted?
Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.
5) How memory is managed in Python?
• Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap.
• The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code.
• Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.
6) What are the tools that help to find bugs or perform static analysis?
PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.
7) What are Python decorators?
A Python decorator is a specific change that we make in Python syntax to alter functions easily.
8) What is the difference between list and tuple?
The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.
9) How are arguments passed by value or by reference?
Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable.
10) What is Dict and List comprehensions are?
They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.
11) What are the built-in type does python provides?
There are mutable and Immutable types of Pythons built in types Mutable built-in types
• List
• Sets
• Dictionaries
Immutable built-in types
• Strings
• Tuples
• Numbers
12) What is namespace in Python?
In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object.
13) What is lambda in Python?
It is a single expression anonymous function often used as inline function.
14) Why lambda forms in python does not have statements?
A lambda form in python does not have statements as it is used to make new function object and then return them at runtime.
15) What is pass in Python?
Pass means, no-operation Python statement, or in other words it is a place holder in compound statement, where there should be a blank left and nothing has to be written there.
16) In Python what are iterators?
In Python, iterators are used to iterate a group of elements, containers like list.
17) What is unittest in Python?
A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections etc.
18) In Python what is slicing?
A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known as slicing.
19) What are generators in Python?
The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.
20) What is docstring in Python?
A Python documentation string is known as docstring, it is a way of documenting Python functions, modules and classes. 
21) How can you copy an object in Python?
To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them.
22) What is negative index in Python?
Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.
23) How you can convert a number to a string?
In order to convert a number into a string, use the inbuilt function str(). If you want a octal or hexadecimal representation, use the inbuilt function oct() or hex().
24) What is the difference between Xrange and range?
Xrange returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is.
25) What is module and package in Python?
In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.
The folder of Python program is a package of modules. A package can have modules or subfolders.
26) What is Python?
Python is an object oriented and open-source programming language, which supports structured and functional built-in data structures. With a placid and easy-to -understand syntax, Python allows code reuse and modularity of programs. The built-in DS in Python makes it a wonderful option for Rapid Application Development (RAD). The coding language also encourages faster editing, testing and debugging with no compilation steps.
27) What are the standard data types supported by Python?
It supports six data types:
1. Number : object stored as numeric value
2. String : object stored as string
3. Tuple : data stored in the form of sequence of immutable objects
4. Dictionary (dicts): associates one thing to another irrespective of the type of data, most useful container (called hashes in C and Java)
5. List : data stored in the form of a list sequence
6. Set (frozenset): unordered collection of distinct objects
28) Explain built-in sequence types in Python Programming?
It provides two built in sequence types-
1. Mutable Type : objects whose value can be changed after creation, example: sets, items in the list, dictionary
2. Immutable type : objects whose value cannot be changed once created, example: number, Boolean, tuple, string
29) Explain the use of iterator in Python?
Python coding uses Iterator to implement the iterator protocol, which enables traversing trough containers and group of elements like list.The two important methods include _iter_() returning the iterator object and next() method for traversal.
30) Define Python slicing ?
The process of extracting a range of elements from lists, arrays, tuples and custom Python data structures as well. It works on a general start and stop method: slice (start, stop, increment)
31) How can you compare two lists in Python?
We can simply perform it using compare function – cmp(rvhtechlist1, rvhtechlist2)
def cmp(rvhtechlist1, rvhtechlist2):
for val in rvhtechlist1:
if val in rvhtechlist2:
returnTrue
returnFalse
32) What is the use of // operator?
‘//’ is a Floor Divisionoperator, which divides two operands with the result as quotient showing only digits before decimal point.For instance, 6//3 = 2 and 6.0//3.0 = 2.0
33) Define docstring in Python with example.
A string literal occurring as the first statement (like a comment) in any module, class, function or method is referred as docstring in Python. This kind of string becomes the _doc_ special attribute of the object and provides an easy way to document a particular code segment. Most modules do contain docstrings and thus, the functions and classes extracted from the module also consist of docstrings.
34) What function randomizes the items of a list in place?
Using shuffle() function
For instance:
import randomize
lst = [2, 18, 8, 4];
randomize.shuffle(lst)
print “Shuffled list : “, lst
random.shuffle(list)
print “Reshuffled list : “, list
35) List five benefits of using Python?
1. Having the built-in data types, Python saves programmer’s time and effort from declaring variables. It has a powerful dict ionary and polymorphic list for automatic declaration. It also ensures better code reusability
2. Highly accessible and easy-to-learn for beginners and a strong ‘glue’ for advanced Professionals consisting fo several high-level modules and operations not performed by other programming languages.
3. Allows easy readability due to use of square brackets for most functions and indexes
4. Python requires no explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically.
5. Python comprises a huge standard library for most Internet platforms like Email, HTML, FTP and other WWW platforms.
36) What are the disadvantages of using Python?
1. Python is slow as compared to other programming languages. Although, this slow pace doesn’t matter much, at times, we need other language to handle performance-critical situations.
2. It is ineffective on mobile platforms; fewer mobile applications are developed using python. The main reason behind its instability on smartphones is Python’s weakest security. There are no good secure cases available for Python until now
3. Due to dynamic typing, Programmers face design restrictions while using the language. The code needs more and more testing before putting it into action since the errors pop up only during runtime.
4. Unlike JavaScript, Python’s features like concurrency and parallelism are not developed for elegant use.
37) Explain the use of split function?
The split() function in Python breaks a string into shorter strings using the defined separator. It renders a list of all words present in the string.
>>> y= ‘true,false,none’
>>> y.split(‘,’)
Result: (‘true’, ‘false’, ‘none’)
What is the use of generators in Python?
Generators are primarily used to return multiple items but one after the other. They are used for iteration in Python and for calculating large result sets. The generator function halts until the next time request is placed.
One of the best uses of generators in Python coding is implementing callback operation with reduced effort and time. They replace callback with iteration. Through the generator approach, programmers are saved from writing a separate callback function and pass it to work-function as it can applying ‘for’ loop around the generator.
38) How to create a multidimensional list in Python?
As the name suggests, a multidimensional list is the concept of a list holding another list, applying to many such lists. It can be one easily done by creating single dimensional list and filling each element with a newly created list.
39) What is lambda?
lambda is a powerful concept used in conjunction with other functions like filter(), map(), reduce(). The major use of lambda construct is
to create anonymous functions during runtime, which can be used where they are created. Such functions are actually known as throw-away functions in Python. The general syntax is lambda argument_list:expression.
For instance:
>>> def rvhtech1 = lambda i, n : i+n
>>> rvhtech(2,2)
4
Using filter()
>> rvhtech= [1, 6, 11, 21, 29, 18, 24]
>> print filter (lambda x: x%3 = = 0, rvhtech)
[6, 21, 18, 24]
40) Define Pass in Python?
The pass statement in Python is equivalent to a null operation and a placeholder, wherein nothing takes place after its execution. It is mostly used at places where you can let your code go even if it isn’t written yet.
If you would set out a pass after the code, it won’t run. The syntax is pass
41) How to perform Unit Testing in Python?
Referred to as PyUnit, the python Unit testing framework-unittest supports automated testing, seggregating test into collections, shutdown testing code and testing independence from reporting framework. The unittest module makes use of TestCase class for holding and preparing test routines and clearing them after the successful execution.
42) Define Python tools for finding bugs and performing static analysis?
. PyChecker is an excellent bug finder tool in Python, which performs static analysis unlike C/C++ and Java. It also notifies the programmers about the complexity and style of the code. In addition, there is another tool, PyLint for checking the coding standards including the code line length, variable names and whether the interfaces declared are fully executed or not.
43) How to convert a string into list?
Using the function list(string). For instance:
>>> list(‘rvhtech’) in your lines of code will return
[‘i’, ‘n’, ‘t’, ‘e’, ‘l’, ‘l’, ‘i’, ‘p’, ‘a’, ‘a’, ‘t’]
In Python, strings behave like list in various ways. Like, you can access individual characters of a string
>> > y = “rvhtech”
>>> s[2]
‘t’
44) What OS do Python support?
Linux, Windows, Mac OS X, IRIX, Compaq, Solaris

45) Define docstring in Python.
A string literal occurring as the first statement (like a comment) in any module, class, function or method is referred as docstring in Python. This kind of string becomes the _doc_ special attribute of the object and provides an easy way to document a particular code segment. Most modules do contain docstrings and thus, the functions and classes extracted from the module also consist of docstrings.
46) Name the optional clauses used in a ‘try-except’ statement in Python?
While Python exception handling is a bit different from Java, the former provides an option of using a try-except clause where the programmer receives a detailed error message without termination the program. Sometimes, along with the problem, this try-except statement offers a solution to deal with the error.
The language also provides try-except-finally and try-except-else blocks.
47)  How to use PYTHOPATH?
PYTHONPATH is the environment variable consisting of directories. $PYTHONPATH is used for searching the actual list of folders for libraries.
48) Define ‘self’ in Python?
self is a reference to the current instance of the class. It is just like ‘this’ in JavaScript. While we create an instance of a class, that instance has its data, which internally passes a reference to it‘self’

49) Define CGI?
Common Gateway Interface support in Python is an external gateway to interact with HTTP server and other information servers. It consists of a series of standards and instructions defining the exchange of information between a custom script and web server. The HTTP server puts all important and useful information concerning the request in the script environment and then run the script and sends it back in the form of output to the client.
50) What is PYTHONSTARTUP and how is it used?
PYTHONSTARTUP is yet another environment variable to test the Python file in the interpreter using interactive mode. The script file is executed even before the first prompt is seen. Additionally, it also allows reloading of the same script file after being modified in the external editor.
51) What is the return value of trunc() in Python?
truc() returns integer value. Uses the _trunc_ method
>>> import rvhtech
rvhtech.trunc(4.34)
4

52) How to convert a string to an object in Python?
To convert string into object, Python provides a function eval(string). It allows the Python code to run in itself
53) Is there any function to change case of all letters in the string?
Yes, Python supports a function swapcase(), which swaps the current letter case of the string. This method returns a copy of the string with the string case swapped.
54) What is pickling and unpickling in Python?
The process of Pickling relates to the Pickle module. Pickle is a general module that acquires a python object and converts it into string. It further dumps that string object into a file by using dump () function.
Pickle comprises two methods:
Dump (): dumps an object to a file object
and Load (): loads an object from a file object
Unpickling is the reacquiring process to perform retrieval of the original Python object from the stored string for reuse.
55) What are the rules for local and global variables in Python?
Local and global variables – 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…
We will continuously update python interview questions and answers in this site with real time scenarios by python experts.You can request for python interview questions and answers pdf in the Contact us form.