bing
Flat 10% & upto 50% off + 10% Cashback + Free additional Courses. Hurry up
×
UPTO
50%
OFF!

Top Python Interview Questions And Answers

Python Interview Questions
Here are top 51 objective type sample Python Interview questions and their answers are given just below to them. These sample questions are framed by experts from Intellipaat who trains for Python training to give you an idea of type of questions which may be asked in interview. We have taken full care to give correct answers for all the questions. Do comment your thoughts Happy Job Hunting!

Python Interview question

Top Answers to Python Interview Questions

1. Compare Java & Python
Criteria Java Python
Ease of use Good Very Good
Speed of coding Average Excellent
Data types Static typed Dynamically typed
Data Science & machine learning applications Average Very Good
2. What is Python?

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.

3. What is the purpose of PYTHONPATH environment variable?

PYTHONPATH − It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer

CTA

Learn for free ! Subscribe to our youtube Channel.

4. What is the purpose of PYTHONSTARTUP,PYTHONCASEOK,PYTHONHOME,PYTHONSTARTUP environment variables?

PYTHONSTARTUP − It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH

PYTHONCASEOK − It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.

PYTHONHOME − It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.

5. What are the supported data types in Python?

Python has five standard data types −

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary
6. What is the difference between list and tuples?
LIST TUPLES
Lists are mutable i.e they can be edited. Tuples are immutable (tuples are lists which can’t be edited).
Lists are slower than tuples. Tuples are faster than list.
Syntax: list_1 = [10, ‘Chelsea’, 20] Syntax: tup_1 = (10, ‘Chelsea’ , 20)
CTA
Become Python Certified in 24 hrs.
CLICK HERE

close

7. How is memory managed in Python?
  1. 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.
  2. 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.
  3. 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.
8. Explain Inheritance in Python with an example.

Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.

They are different types of inheritance supported by Python:

  1. Single Inheritance – where a derived class acquires the members of a single super class.
  2. Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 is inherited from base2.
  3. Hierarchical inheritance – from one base class you can inherit any number of child classes
  4. Multiple inheritance – a derived class is inherited from more than one base class.
9. Whenever Python exits, why isn’t all the memory de-allocated?
  1. Whenever Python exits, especially those Python modules which are having circular references to other objects or the objects that are referenced from the global namespaces are not always de-allocated or freed.
  2. It is impossible to de-allocate those portions of memory that are reserved by the C library.
  3. On exit, because of having its own efficient clean up mechanism, Python would try to de-allocate/destroy every other object.
10. What is dictionary in Python?

The built-in datatypes in Python is called dictionary. It defines one-to-one relationship between keys and values. Dictionaries contain pair of keys and their corresponding values. Dictionaries are indexed by keys.

Let’s take an example:

The following example contains some keys. Country, Capital & PM. Their corresponding values are India, Delhi and Modi respectively.

dict={‘Country’:’India’,’Capital’:’Delhi’,’PM’:’Modi’}

print dict[Country]

11. Write a one-liner that will count the number of capital letters in a file. Your code should work even if the file is too big to fit in memory.

Let us first write a multiple line solution and then convert it to one liner code.

1 with open(SOME_LARGE_FILE) as fh:

2 count = 0
3 text = fh.read()
4 for character in text:
5 if character.isupper():
6 count += 1

 

12. Write a sorting algorithm for a numerical dataset in Python.

The following code can be used to sort a list in Python:

list = [“1”, “4”, “0”, “6”, “9”]

list = [int(i) for i in list]

list.sort()

print (list)

13. How will you reverse a list?

list.reverse() − Reverses objects of list in place.

14. How will you remove last object from a list?

list.pop(obj=list[-1]) − Removes and returns last object or obj from list.

15. What are negative indexes and why are they used?

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 show the index to represent the string in correct order.

16. Explain split(), sub(), subn() methods of “re” module in Python.

To modify the strings, Python’s “re” module is providing 3 methods. They are:

  • split() – uses a regex pattern to “split” a given string into a list.
  • sub() – finds all substrings where the regex pattern matches and then replace them with a different string
  • subn() – it is similar to sub() and also returns the new string along with the no. of replacements.
17. What is the difference between range & xrange?

For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and x range returns an xrange object.

This means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function to use.

This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It’s a memory hungry beast.

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

19. What is map function in Python?

map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given. #Follow the link to know more similar functions

20. How to get indices of N maximum values in a NumPy array?

We can get the indices of N maximum values in a NumPy array using the below code:
import numpy as np

arr = np.array([1, 3, 2, 4, 5])

print(arr.argsort()[-3:][::-1])

21. What is a Python module?

A module is a Python script that generally contains import statements, functions, classes and variable definitions, and Python runnable code and it “lives” file with a ‘.py’ extension. zip files and DLL files can also be modules.Inside the module, you can refer to the module name as a string that is stored in the global variable name .

22. Name the File-related modules in Python?

Python provides libraries / modules with functions that enable you to manipulate text files and binary files on file system. Using them you can create files, update their contents, copy, and delete files. The libraries are : os, os.path, and shutil.

Here, os and os.path – modules include functions for accessing the filesystem

shutil – module enables you to copy and delete the files.

23. Explain the use of with statement?

In python generally “with” statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. “with” statement makes the exception handling simpler by providing cleanup activities.

General form of with:

with open(“filename”, “mode”) as file-var:

processing statements

note: no need to close the file by calling close() upon file-var.close()

24. Explain all the file processing modes supported by Python?

Python allows you to open files in one of the three modes. They are:

read-only mode, write-only mode, read-write mode, and append mode by specifying the flags “r”, “w”, “rw”, “a” respectively.

A text file can be opened in any one of the above said modes by specifying the option “t” along with

“r”, “w”, “rw”, and “a”, so that the preceding modes become “rt”, “wt”, “rwt”, and “at”.A binary file can be opened in any one of the above said modes by specifying the option “b” along with “r”, “w”, “rw”, and “a” so that the preceding modes become “rb”, “wb”, “rwb”, “ab”.

25. How many kinds of sequences are supported by Python? What are they?

Python supports 7 sequence types. They are str, list, tuple, unicode, byte array, xrange, and buffer. where xrange is deprecated in python 3.5.X.

26. How do you perform pattern matching in Python? Explain

Regular Expressions/REs/ regexes enable us to specify expressions that can match specific “parts” of a given string. For instance, we can define a regular expression to match a single character or a digit, a telephone number, or an email address, etc.The Python’s “re” module provides regular expression patterns and was introduce from later versions of Python 2.5. “re” module is providing methods for search text strings, or replacing text strings along with methods for splitting text strings based on the pattern defined.

27. How to display the contents of text file in reverse order?
  1. convert the given file into a list.
  2. reverse the list by using reversed()
  3. Eg: for line in reversed(list(open(“file-name”,”r”))):
  4. print(line)
28. What is the difference between NumPy and SciPy?
  1. In an ideal world, NumPy would contain nothing but the array data type and the most basic operations: indexing, sorting, reshaping, basic element wise functions, et cetera.
  2. All numerical code would reside in SciPy. However, one of NumPy’s important goals is compatibility, so NumPy tries to retain all features supported by either of its predecessors.
  3. Thus NumPy contains some linear algebra functions, even though these more properly belong in SciPy. In any case, SciPy contains more fully-featured versions of the linear algebra modules, as well as many other numerical algorithms.
  4. If you are doing scientific computing with python, you should probably install both NumPy and SciPy. Most new features belong in SciPy rather than NumPy.
29. Which of the following is an invalid statement?

a) abc = 1,000,000

b) a b c = 1000 2000 3000

c) a,b,c = 1000, 2000, 3000

d) a_b_c = 1,000,000

Answer: b

30. What is the output of the following? try: if '1' != 1: raise

a) some Error has  occured

b) some Error has not occured

c) invalid code

d) none of the above

Answer: C

31. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1] ?

25

32. To open a file c:\scores.txt for writing?

fileWriter = open(“c:\\scores.txt”, “w”)

33. Name few Python modules for Statistical, Numerical and scientific computations ?

numPy – this module provides an array/matrix type, and it is useful for doing computations on arrays. scipy – this module provides methods for doing numeric integrals, solving differential equations, etc pylab – is a module for generating and saving plots

34. What is TkInter?

TkInter is Python library. It is a toolkit for GUI development. It provides support for various GUI tools or widgets (such as buttons, labels, text boxes, radio buttons, etc) that are used in GUI applications. The common attributes of them include Dimensions, Colors, Fonts, Cursors, etc.

35. Is Python object oriented? what is object oriented programming?

Yes. Python is Object Oriented Programming language. OOP is the programming paradigm based on classes and instances of those classes called objects. The features of OOP are:

Encapsulation, Data Abstraction, Inheritance, Polymorphism.

36. What is multithreading? Give an example.

It means running several different programs at the same time concurrently by invoking multiple threads. Multiple threads within a process refer the data space with main thread and they can communicate with each other to share information more easily.Threads are light-weight processes and have less memory overhead. Threads can be used just for quick task like calculating results and also running other processes in the background while the main program is running.

37. Does Python supports interfaces like in Java? Discuss.

Python does not provide interfaces like in Java. Abstract Base Class (ABC) and its feature are provided by the Python’s “abc” module. Abstract Base Class is a mechanism for specifying what methods must be implemented by its implementation subclasses. The use of ABC’c provides a sort of “understanding” about methods and their expected behaviour. This module was made available from Python 2.7 version onwards.

38. What are Accessors, mutators, @property?

Accessors and mutators are often called getters and setters in languages like “Java”. For example, if x is a property of a user-defined class, then the class would have methods called setX() and getX(). Python has an @property “decorator” that allows you to ad getters and setters in order to access the attribute of the class.

39. Differentiate between append() and extend() methods.?

Both append() and extend() methods are the methods of list. These methods a re used to add the elements at the end of the list.

append(element) – adds the given element at the end of the list which has called this method.

extend(another-list) – adds the elements of another-list at the end of the list which is called the extend method.

40. Name few methods that are used to implement Functionally Oriented Programming in Python?

Python supports methods (called iterators in Python3), such as filter(), map(), and reduce(), that are very useful when you need to iterate over the items in a list, create a dictionary, or extract a subset of a list.

filter() – enables you to extract a subset of values based on conditional logic.

map() – it is a built-in function that applies the function to each item in an iterable.

reduce() – repeatedly performs a pair-wise reduction on a sequence until a single value is computed.

41. What is the output of the following?

x = [‘ab’, ‘cd’]
print(len(map(list, x)))

A TypeError occurs as map has no len().

42. What is the output of the following?

x = [‘ab’, ‘cd’]
print(len(list(map(list, x))))

Explanation: The length of each string is 2.

43. Which of the following is not the correct syntax for creating a set?
  1. a) set([[1,2],[3,4]])
  2. b) set([1,2,2,3,4])
  3. c) set((1,2,3,4))
  4. d) {1,2,3,4}

Answer : a

Explanation : The argument given for the set must be an iterable.

44. Explain a few methods to implement Functionally Oriented Programming in Python.

Sometimes, when we want to iterate over a list, a few methods come in handy.

  1. filter()

Filter lets us filter in some values based on conditional logic.

>>> list(filter(lambda x:x>5,range(8)))

[6, 7]

  1. map()

Map applies a function to every element in an iterable.

>>> list(map(lambda x:x**2,range(8)))

[0, 1, 4, 9, 16, 25, 36, 49]

  1. reduce()

Reduce repeatedly reduces a sequence pair-wise until we reach a single value

>>> from functools import reduce

>>> reduce(lambda x,y:x-y,[1,2,3,4,5])

-13

45. Explain database connection in Python Flask?

Flask supports database powered application (RDBS). Such system requires creating a          schema, which requires piping the shema.sql file into a sqlite3 command.  So you need to install   sqlite3 command in order to create or initiate the database in Flask.

Flask allows to request database in three ways

  • before_request() : They are called before a request and pass no arguments
  • after_request() : They are called after a request and pass the response that will be sent to the client
  • teardown_request(): They are called in situation when exception is raised, and response are not guaranteed. They are called after the response been constructed. They are not allowed to modify the request, and their values are ignored.
46. Write a Python function that checks whether a passed string is palindrome Or not? Note: A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.

def isPalindrome(string):
left_pos = 0
right_pos = len(string) – 1

while right_pos >= left_pos:
if not string[left_pos] == string[right_pos]:
return False
left_pos += 1
right_pos -= 1
return True
print(isPalindrome(‘aza’))

47. Write a Python program to calculate the sum of a list of numbers.

def list_sum(num_List):
if len(num_List) == 1:
return num_List[0]
else:
return num_List[0] + list_sum(num_List[1:])

print(list_sum([2, 4, 5, 6, 7]))

Sample Output:

24

48. How to retrieve data from a table in MySQL database through Python code? Explain.
  1. import MySQLdb module as : import MySQLdb
  2. establish a connection to the database.
  3. db = MySQLdb.connect(“host”=”local host”, “database-user”=”user-name”, “password”=”password”, “database-name”=”database”)
  4. initialize the cursor variable upon the established connection: c1 = db.cursor()
  5. retrieve the information by defining a required query string. s = “Select * from dept”
  6. fetch the data using fetch() methods and print it. data = c1.fetch(s)
  7. close the database connection. db.close()
49. Write a Python program to read a random line from a file.

import random
def random_line(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)
print(random_line(‘test.txt’))

50. Write a Python program to count the number of lines in a text file.

def file_lengthy(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
print(“Number of lines in the file: “,file_lengthy(“test.txt”))

Python Programming

"9 Responses on Top Python Interview Questions And Answers"

  1. shashidhar devraj says:

    Great work..!! Really helpfull..!!

  2. Bhandranti says:

    Thanks to these questions, I got a job offer in a multi million dollar company! Thanks a lot guys, Keep up the good work.

  3. Rosalia Fotolela says:

    Wow, such a useful guide….thank you for sharing!!

  4. Waheed says:

    Very helpful and informative.
    Thanks!

  5. Lakshmikanth says:

    I’m really excited to learn this questions and wholehearted thanks to people who made this possible.

  6. Luis says:

    very good, allows you to check your knowledge

  7. Gaurav B says:

    I read given questions and answers i like it, it is very helpful for a new comer or experience programmer in python.

  8. Justin says:

    Good..helpful in increasing Python knowledge

  9. Mayank says:

    All the content is important for interview..thanks for providing such a useful information regarding python.

Leave a Message

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.
top

Sales Offer

Sign Up or Login to view the Free Top Python Interview Questions And Answers.