Python Interview Questions And Answers For Experienced

Python Interview Questions And Answers For Experienced. Here Coding compiler sharing a list of 165+ interview questions on python prepared by the expert Python developers. This list consists of Python basic interview questions to advanced Python interview questions for 1 year experienced, 2 years experienced, 3 years experienced, 4 years experienced and 5+ years experienced developers.

These Python questions were prepared by Python expert developers and asked in various Python Interviews. We hope that this list will help you to crack your next Python job interview. All the best for your future and happy learning.

Table of Contents

Python Interview Questions

  1. What is Python programming language?
  2. Who created Python?
  3. What are the features of Python?
  4. What are the programming-language features of Python?
  5. What is Python used for?
  6. What is Python Package Manager (PyPM)?
  7. What is Python web application framework?
  8. Name few Python web application frameworks?
  9. Name few Python Checkers for Debugging?
  10. What is the Python interactive console or Python shell?
  11. What is the difference between Python 2 and Python 3?
  12. Name few Python Shells?
  13. What is the Python IDLE?
  14. What is an interpreter for Python?
  15. How do you run a Python script?
  16. How many modes are there in Python?
  17. What is a Script mode?
  18. What is the interactive mode?
  19. What is the use of Pycharm?
  20. Why is Python so powerful?

Python Interview Questions And Answers

Here you can read a list of 165 Python interview questions, Python programming questions, Python real-time scenarios. Let’s start learning.

Also Read: Python Coding Interview Questions

Python Basic Interview Questions

1) What is Python programming language?

A) Python is an interpreted high-level programming language for general-purpose programming.

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.

2) Who created Python?

A) Created by Guido van Rossum and first released in 1991.

3) What are the features of Python?

A) Some of Python’s notable features:

Uses an elegant syntax, making the programs you write easier to read.

Is an easy-to-use language that makes it simple to get your program working. This makes Python ideal for prototype development and other ad-hoc programming tasks, without compromising maintainability.

Comes with a large standard library that supports many common programming tasks such as connecting to web servers, searching text with regular expressions, reading and modifying files.

Python’s interactive mode makes it easy to test short snippets of code. There’s also a bundled development environment called IDLE.

Is easily extended by adding new modules implemented in a compiled language such as C or C++.

Can also be embedded into an application to provide a programmable interface.

Runs anywhere, including Mac OS X, Windows, Linux, and Unix, with unofficial builds also available for Android and iOS.

4) What are the programming-language features of Python?

A) programming-language features of Python are:

A variety of basic data types are available: numbers (floating point, complex, and unlimited-length long integers), strings (both ASCII and Unicode), lists, and dictionaries.

Python supports object-oriented programming with classes and multiple inheritance.

Code can be grouped into modules and packages.

The language supports raising and catching exceptions, resulting in cleaner error handling.

Data types are strongly and dynamically typed. Mixing incompatible types (e.g. attempting to add a string and a number) causes an exception to be raised, so errors are caught sooner.

Python contains advanced programming features such as generators and list comprehensions.

Python’s automatic memory management frees you from having to manually allocate and free memory in your code.

5) What is Python used for?

A) Python is a general-purpose programming language, it can be used to test microchips, building web applications, desktop applications, video games, artificial intelligence, machine learning and data science. With the help of third-party libraries, we can build any kind of applications using Python programming language.

6) What is Python Package Manager (PyPM)?

A) Python Package Manager (PyPM) is a Python utility intended to simplify the tasks of locating, installing, upgrading and removing Python packages. It can determine if the most recent version of a software package is installed on a system, and can install or upgrade that package from a local or remote host.

7) What is Python web application framework?

A) Web application frameworks, or simply “web frameworks”, are the de facto way to build web-enabled applications. From simple blogs to complex AJAX-rich applications.

8) Name few Python web application frameworks?

A) There are many Python web application frameworks are there, they are

django – Django is a high-level Python Web framework.

web2py – An open source full-stack python web framework for scalable, secure and portable

flask – A lightweight Python web framework based on Werkzeug and Jinja 2.

grok – An open-source Web framework based on Zope Toolkit technology.

tornado – Tornado is a scalable, non-blocking web server and web application framework.

cherrypy – CherryPy is an object-oriented web application framework.

turbogears – A Python-based database web app framework with Ajax integration.

google app engine – A platform for developing and hosting web applications in Google-managed data centers, including Python.

pylons – A lightweight web framework emphasizing flexibility and rapid development.

9) Name few Python Checkers for Debugging?

A) There are many debugging tools out there, few of them are:

Pychecker – A tool for finding bugs in python source code.

pudb – PuDB is a full-screen, console-based visual debugger for Python.

pdb – The module pdb defines an interactive source code debugger for Python programs.

pylint – Analyzes Python source code looking for bugs and signs of poor quality.

10) What is the Python interactive console or Python shell?

A) The Python interactive console, also known as the Python interpreter or Python shell. It provides programmers with a quick way to execute commands and try out or test code without creating a file.

Providing access to all of Python’s built-in functions and any installed modules, command history, and auto-completion, the interactive console offers the opportunity to explore Python and the ability to paste code into programming files when you are ready.

Python Interview Questions For Beginners

11) What is the difference between Python 2 and Python 3?

A) Python 2.7 and Python 3 share many similar capabilities, they should not be thought of as entirely interchangeable. Though you can write good code and useful programs in either version, it is worth understanding that there will be some considerable differences in code syntax and handling.

12) Name few Python Shells?

A) Here is the list of few Python shells,

  • dreampie – A graphical interactive Python shell which is designed to be reliable and fun.
  • ipython – A development shell both written in and designed for Python.
  • bpython – A fancy interface to the Python interpreter for Linux, BSD, OS X and Windows.

13) What is the Python IDLE?

A) IDLE (short for integrated development environment or integrated development and learning environment) is an integrated development environment for Python, which has been bundled with the default implementation of the language since 1.5.2b1.

14) What is an interpreter for Python?

A) The interpreter operates somewhat like the Unix shell: when called with standard input connected to a tty device, it reads and executes commands interactively; when called with a file name argument or with a file as standard input, it reads and executes a script from that file.

15) How do you run a Python script?

A) Run a Python script under Windows with the Command Prompt. Note that you must use the full path of the Python interpreter. If you want to simply type python.exe C:\Users\Username\Desktop\my_python_script.py you must add python.exe to your PATH environmental variable.

Python Interview Questions And Answers For Beginners

16) How many modes are there in Python?

A) Python has two basic modes: script and interactive.

17) What is a Script mode?

A) The normal mode is the script mode where the scripted and finished .py files are run in the Python interpreter.

18) What is the interactive mode?

A) Interactive mode is a command line shell which gives immediate feedback for each statement, while running previously fed statements in active memory.

19) What is the use of Pycharm?

A) PyCharm is an Integrated Development Environment (IDE) used in computer programming, specifically for the Python language. It provides code analysis, a graphical debugger, an integrated unit tester, integration with version control systems (VCSes), and supports web development with Django.

20) Why is Python so powerful?

A) Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike. Python’s readability makes it a great first programming language — it allows you to think like a programmer and not waste time understanding the mysterious syntax that other programming languages can require.

Python Interview Questions For Freshers

21) What is the script in python?

A) Scripts are reusable. Basically, a script is a text file containing the statements that comprise a Python program. Once you have created the script, you can execute it over and over without having to retype it each time. Scripts are editable.

22) What is Anaconda program?

A) Anaconda (Python distribution) Anaconda is a freemium open source distribution of the Python and R programming languages for large-scale data processing, predictive analytics, and scientific computing, that aims to simplify package management and deployment.

23) Where do you use Python programming? Can you describe in detail?

A) Python is a scripting language like PHP, Perl, Ruby and so much more. It can be used for web programming (django, Zope, Google App Engine, and much more). But it also can be used for desktop applications (Blender 3D, or even for games pygame). Python can also be translated into binary code like java.

24) What is a REPL in Python?

A) A Read–Eval–Print Loop (REPL), also known as an interactive top-level or language shell, is a simple, interactive computer programming environment that takes single user inputs (i.e. single expressions), evaluates them, and returns the result to the user; a program written in a REPL environment is executed piecewise.

25) Is Python is a case sensitive?

A) Python language is case sensitive.

Case sensitive means that a is different from A.

The variable of Michel is different from the variable of michel.

If we assume a value for a (lowercase a) and then call A (uppercase A), we will see the following error message:

Copy
>>>a=2
>>>A

Traceback (most recent call last):
File “<pyshell#1>”, line 1, in <module>
A
NameError: name ‘A’ is not defined
>>>
In the above example, A is not assigned any value.

Thus, when we call it by typing A, we will receive an error message. Note that the last line mentions NameError instead of TypeError. In Python, we use name for variables.

Python Interview Questions And Answers For Freshers

26) What is a file in Python?

A) A file is some information or data which stays in the computer storage devices. Python gives you easy ways to manipulate these files. Generally we divide files in two categories, text file and binary file. Text files are simple text where as the binary files contain binary data which is only readable by computer.

27) What is the input function in Python?

A) Input can come in various ways, for example from a database, another computer, mouse clicks and movements or from the internet. Yet, in most cases the input stems from the keyboard. For this purpose, Python provides the function input(). input has an optional parameter, which is the prompt string.

28) Is Python a compiled or interpreted language?

A) Python will fall under byte code interpreted. . py source code is first compiled to byte code as .pyc. This byte code can be interpreted (official CPython), or JIT compiled (PyPy). Python source code (.py) can be compiled to different byte code also like IronPython (.Net) or Jython (JVM).

29) How do I run a Python script?

A) Run a Python script under Windows with the Command Prompt. Note that you must use the full path of the Python interpreter. If you want to simply type python.exe C:\Users\Username\Desktop\my_python_script.py you must add python.exe to your PATH environmental variable.

30) What is the directory in Python?

A) A directory or folder is a collection of files and sub directories. Python has the os module, which provides us with many useful methods to work with directories (and files as well).

Python Interview Questions For 1 Year Experienced

31) What is a dictionary in python?

A) A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated (or mapped) to a value. The values of a dictionary can be any Python data type. So dictionaries are unordered key-value-pairs.

32) What is the meaning of stdin in Python?

A) When you run your Python program, sys.stdin is the file object connected to a standard input (STDIN), sys.stdout is the file object for standard output (STDOUT), and sys.stderr is the file object for standard error (STDERR).

33) What is PyTables?

A) PyTables is a package for managing hierarchical datasets and designed to efficiently and easily cope with extremely large amounts of data. You can download PyTables and use it for free.

34) What is the output of this line?

>>>100/(1+0.1)^2

A) It will give the error message saying that ^ is not supported.

>>>100/(1+0.1)^2
Traceback (most recent call last):
File “<psyhell#1>, line 1, in <module>
100/(1+0.1)^2
TypeError: unsupported operand type(s) for ^: ‘float’ and ‘int’
>>>

35) How do you find the current version of Python?

A) By using sys.version we can fidn the current version of Python. See below example,

>>>import sys
>>>sys.version
‘3.6.4 (v3.6.4:d047928ae3f6, April 16 2018, 00:10:25) [MSC v.1600 64 bit (Intel)]’
>>>

Python Questions And Answers For 1 Year Experienced

36) What is the difference between interpreted and compiled languages?

A) Java (interpreted) and C (or C++) (compiled) might have been a better example. Basically, compiled code can be executed directly by the computer’s CPU. The code of interpreted languages however must be translated at run-time from any format to CPU machine instructions. This translation is done by an interpreter.

37) Is Python Interpreted or Compiled?

A) py source code is first compiled to byte code as .pyc. This byte code can be interpreted (official CPython), or JIT compiled (PyPy). Python source code (.py) can be compiled to different byte code also like IronPython (.Net) or Jython (JVM). There are multiple implementations of Python language.

38) What is an interpreter for Python?

A) The interpreter operates somewhat like the Unix shell: when called with standard input connected to a tty device, it reads and executes commands interactively; when called with a file name argument or with a file as standard input, it reads and executes a script from that file.

39) Is Python a procedural language?

A) Python is a multi-paradigm; you can write programs or libraries that are largely procedural, object-oriented, or functional.

40) What is lambda function in Python?

A) The lambda operator or lambda function is a way to create small anonymous functions, i.e. functions without a name. These functions are throw-away functions, i.e. they are just needed where they have been created. Lambda functions are mainly used in combination with the functions filter(), map() and reduce().

Python Advanced Interview Questions

41) What is a list in Python?

A) A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item.

42) What is the input function in Python?

A) Input can come in various ways, for example from a database, another computer, mouse clicks and movements or from the internet. Yet, in most cases the input stems from the keyboard. For this purpose, Python provides the function input(). input has an optional parameter, which is the prompt string.

43) What is standard output in Python?

A) Standard output and standard error (commonly abbreviated stdout and stderr) are pipes that are built into every UNIX system. When you print something, it goes to the stdout pipe; when your program crashes and prints out debugging information (like a traceback in Python), it goes to the stderr pipe.

44) What is the meaning of DEF in Python?

A) A function in Python is defined by a def statement.

Example:
def f():
print(‘In function f’)
print(‘When does this print?’)

Best Python Interview Questions

45) How do you call functions in Python?

A) We will see with the example:

# Defining a function
def my_function():

print(“Hello From My Function!”)

# print a simple greeting by calling a function
my_function()

46) What is self in Python?

A) The first argument of every class method, including init, is always a reference to the current instance of the class. By convention, this argument is always named self. In the init method, self-refers to the newly created object; in other class methods, it refers to the instance whose method was called.

47) How many coding styles are there in Python?

A) There are four main Python coding styles: imperative, functional, object-oriented, and procedural.

48) What is the use of MAP in Python?

A) The map function is the simplest one among Python built-ins used for functional programming. These tools apply functions to sequences and other iterables. The filter filters out items based on a test function which is a filter and apply functions to pairs of item and running result which is reduce.

49) What is a sequence in Python?

A) In Python, sequence is the generic term for an ordered set. There are several types of sequences in Python, the following three are the most important. Lists are the most versatile sequence type. The elements of a list can be any object, and lists are mutable – they can be changed.

50) What does ORD () do in Python?

A) ord(c) in Python Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string.

For example, ord(‘a’) returns the integer 97.

Python Interview Questions For 2 Years Experienced

51) What is a tuple in Python?

A) A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists.

52) What is a list in Python?

A) A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item.

53) What is the difference between a list and a tuple?

A) List is mutable and tuples is immutable. The main difference between mutable and immutable is memory usage when you are trying to append an item. When you create a variable, some fixed memory is assigned to the variable. If it is a list, more memory is assigned than actually used.

54) What is a cast in Python?

A) Casting is when you convert a variable value from one type to another. This is, in Python, done with functions such as int() or float() or str() . A very common pattern is that you convert a number, currently as a string into a proper number.

55) Can you explain this why are we getting an error here?

>>>sqrt(3)
Traceback (most recent call last):
File “<pyshell#17>”, line 1, in <module>
sqrt(3)
NameError: name ‘sqrt’ is not defined

A) In the above code, sqrt() function is available in the “math” module and that we have to load import the “math” module before we can call the “sqrt()” functions.

Python Top Interview Questions

56) What is a module in python?

A) In Python, module is a package that contains a set of functions to do a specific task. For example “math” module provides some math related functions like sqrt().

57) What is the use of dir() function?

A) After assigning values to a few variables, we could use the dir() function to show their existence. In the following example, variables p, av, and d are shown among other names.

>>>av=100
>>>p=0.1
>>>d=5
>>>dir()
[‘p’, ‘av’, ‘d’]

58) How can you unsign or delete variable in Python?

A) Whenever we write code for any application, it might be a good practice to delete those variables that we no longer need. In this case, we could use the del() function to remove or unsign a variable.

59) What is tuple in Python?

A) In Python, a tuple is a data type or object. A tuple could contain multiple data types such as integer, float, string, and even another tuple. All data items are included in a pair of parentheses as shown in the following example:

>>>x=(‘John’,21)
>>>x
(‘John’, 21)

60) How can you find length of a tuple in Python?

A) Like with strings and lists, we can calculate the length of a tuple by using len().

Python Interview Questions For 3 Years Experienced

61) What is string replication operator in Python?

A) * is the string replication operator, repeating a single string however many times you would like through the integer you provide.

Example: Let’s print out “Python” 5 times without typing out “Python” 5 times with the * operator:

print(“Python” * 5)

Output: PythonPythonPythonPythonPython

62) What is the output of this below query?

ss = “Python Programming!”
print(ss[5])

A) Output of the above code is: n

63) What is GIL in Python?

A) In Python, GIL (Global Interpreter Lock) is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once.

64) What is meant by mutex in Python?

A) In Python programming, a mutex (mutual exclusion object) is a program object that is created so that multiple program thread can take turns sharing the same resource, such as access to a file.

65) Is Python supports Multithreading?

A) Yes Python supports multithreading concept with the help of Global Interpreter Lock (GIL).

Python Advanced Interview Questions And Answers

66) Explain the use of Ternary operator in Python?

A) In Python, Ternary operator added in the version 2.5. It is used as a conditional statement, it consists of the true or false values. Ternary operator evaluates the statement and stores true or false values.

Python Ternary Operator Syntax :

[on_true] if [expression] else [on_false]

Python Ternary Operator Example:

a, b = 22, 35

# Checking the minimum number and storing in mini
mini = a if a < b else b

print(mini)

Output: 22

67) What is memory management in Python?

A) Memory management in Python involves a private heap containing all Python objects and data structures. The management of this private heap is ensured internally by the Python memory manager.

68) What are the components of Python Memory Manager?

A) The Python memory manager has different components which deal with various dynamic storage management aspects, like sharing, segmentation, preallocation or caching.

69) What are the types of inheritance in Python?

A) Python supports different types of inheritance, they are:

  • Single Inheritance
  • Multi-level Inheritance
  • Hierarchical Inheritance
  • Multiple Inheritance

Advanced Python Interview Questions

70) What is superclass and subclass in Python?

A) In Python, the parent class as a superclass. The class that’s derived from the superclass is called the subclass.

71) What is MRO in Python?

A) In multiple inheritance, the order in which base classes are searched when looking for a method is often called the Method Resolution Order (MRO).

72) What is super () in Python?

A) Super() is used to return a proxy object that delegates method calls to a parent or sibling class of type.

73) What is overriding in Python?

A) In Python, Overriding is the ability of a class to change the implementation of a method provided by one of its ancestors. Overriding is a very important part of OOP since it is the feature that makes inheritance exploit its full power.

74) What is an abstract class in Python?

A) An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. Subclasses of an abstract class in Python are not required to implement abstract methods of the parent class.

75) Is multiple inheritances possible in python?

A) Multiple inheritance on the other hand is a feature in which a class can inherit attributes and methods from more than one parent class. Python has a sophisticated and well-designed approach to multiple inheritance.

Advanced Python Interview Questions And Answers

76) What is operator overloading in python?

A) Operator overloading (less commonly known as ad-hoc polymorphism) is a specific case of polymorphism (part of the OO nature of the language) in which some or all operators like +, = or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments.

Example: You can use + operator for adding numbers and at the same time to concatenate strings. It is possible because + operator is overloaded by both int class and str class. The operators are actually methods defined in respective classes.

77) What is a decorator in Python?

A) Decorators provide a simple syntax for calling higher-order functions. By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.

78) Why do you use abstract classes?

A) Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.

79) What is a constructor in Python?

A) A constructor is a special kind of method that Python calls when it instantiates an object using the definitions found in your class. Python relies on the constructor to perform tasks such as initializing (assigning values to) any instance variables that the object will need when it starts.

Python Interview Questions For 4 Years Experienced

80) What is a model in python?

A) A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table.

81) What is repr() function in Python?

A) repr() function evaluate the string representation of an object.

82) What is a Numpy in Python?

A) NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.

83) What is a panda in Python?

A) pandas is a Python package providing fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive. It aims to be the fundamental high-level building block for doing practical, real world data analysis in Python.

84) What is yield in Python?

A) The yield statement in Python is used to define generators, replacing the return of a function to provide a result to its caller without destroying local variables. Unlike a function, where on each call it starts with new set of variables, a generator will resume the execution where it was left off.

Python Interview Questions For Experienced

85) What is an iterator in python?

A) In Python, an iterator is an object which implements the iterator protocol. The iterator protocol consists of two methods. The __iter__() method, which must return the iterator object, and the next() method, which returns the next element from a sequence.

86) What is ABS in Python?

A) The abs() function is used to return the absolute value of a number.

Syntax: abs(number)

number can be integer, a floating point number or a complex number. The abs() takes only one argument, a number whose absolute value is to be returned.

87) What is Matplotlib for Python?

A) Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK+.

89) What is a PIL in Python?

A) Python Imaging Library (abbreviated as PIL) (in newer versions known as Pillow) is a free library for the Python programming language that adds support for opening, manipulating, and saving many different image file formats. It is available for Windows, Mac OS X and Linux.

90) What does ORD () do in Python?

A) ord(c) in Python Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string.

Python Interview Questions And Answers For Experienced

91) What is the Scipy?

A) SciPy is an open-source Python library used for scientific computing and technical computing. The NumPy stack is also sometimes referred to as the SciPy stack.

92) What is lambda function in Python?

A) The lambda operator or lambda function is a way to create small anonymous functions, i.e. functions without a name. These functions are throw-away functions, i.e. they are just needed where they have been created. Lambda functions are mainly used in combination with the functions filter(), map() and reduce().

93) What does Isalpha do in Python?

A) In Python, isalpha() is a built-in method used for string handling. The isalpha() methods returns “True” if all characters in the string are alphabets, Otherwise, It returns “False”.

94) What is a Sympy?

A) SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python.

95) What is a data structure in Python?

A) The builtin data structures in Python are: lists, tuples, dictionaries, strings, sets and frozensets. Lists, strings and tuples are ordered sequences of objects. Unlike strings that contain only characters, list and tuples can contain any type of objects.

Interview Questions on Python For Experienced

96) What is coercion?

A) The implicit conversion of an instance of one type to another during an operation which involves two arguments of the same type. For example, int(3.15) converts the floating point number to the integer 3, but in 3+4.5, each argument is of a different type (one int, one float), and both must be converted to the same type before they can be added or it will raise a TypeError.

Without coercion, all arguments of even compatible types would have to be normalized to the same value by the programmer, e.g., float(3)+4.5 rather than just 3+4.5.

97) What is Flask in Python?

A) Flask is a micro web framework written in Python and based on the Werkzeug toolkit and Jinja2 template engine.

98) What is Redis Python?

A) Redis is an in-memory key-value pair NoSQL data store often used for web application sessions, transient data and as a broker for task queues. redis-py is a common Python code library for interacting with Redis.

99) How can you explicitly free memory in Python?

A) In Python, You can force the Garbage Collector to release unreferenced memory with gc.collect().

Example:
import gc
gc.collect()

100) What is Monkey Patching in Python?

A) Monkey patching is reopening the existing classes or methods in class at runtime and changing the behavior, which should be used cautiously, or you should use it only when you really need to.

Python Interview Questions For 5 Years Experienced

101) What is range and xrange in Python?

A) xrange is a sequence object that evaluates lazily. range creates a list, so if you do range(1, 10000000) it creates a list in memory with 9999999 elements. xrange is a generator, so it is a sequence object is a that evaluates lazily.

102) What is pickling and Unpickling?

A) Pickling is the process whereby a Python object hierarchy is converted into a byte stream, and Unpickling – is the inverse operation, whereby a byte stream is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as serialization, marshalling, or flattening.

103) Is there a benefit to using one over the other? In Python 2, they both seem to return the same results:

>>> 6/3
2
>>> 6//3
2

A) In Python 3.0, 5 / 2 will return 2.5 and 5 // 2 will return 2. The former is floating point division, and the latter is floor division, sometimes also called integer division.

In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from __future__ import division, which causes Python 2.x to adopt the behavior of 3.0

Regardless of the future import, 5.0 // 2 will return 2.0 since that’s the floor division result of the operation.

104) What is Python slice()?

A) The slice object is used to slice a given sequence (string, bytes, tuple, list or range) or any object which supports sequence protocol.

105) What is the output of this code?

print(slice(3))

print(slice(1, 5, 2))

A) The above code prints below results,

slice(None, 3, None)
slice(1, 5, 2)

Python Experienced Interview Questions

106) Guess the output?

pyList = [‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]

pyTuple = (‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)

sObject = slice(3)

# slice a list

print(pyList[sObject])

sObject = slice(1, 5, 2)

# slice a tuple

print(pyTuple[sObject])

A) The output would be,

[‘P’, ‘y’, ‘t’]

(‘y’, ‘h’)

107) How to test multiple variables against a value?

I’m trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:

x = 0
y = 1
z = 3
mylist = []

if x or y or z == 0 :
mylist.append(“c”)
if x or y or z == 1 :
mylist.append(“d”)
if x or y or z == 2 :
mylist.append(“e”)
if x or y or z == 3 :
mylist.append(“f”)
which would return a list of

[“c”, “d”, “f”]
Is something like this possible?

A) You misunderstand how boolean expressions work; they don’t work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:

if x == 1 or y == 1 or z == 1:
x and y are otherwise evaluated on their own (False if 0, True otherwise).

You can shorten that using a containment test against a tuple:

if 1 in (x, y, z):
or better still:

if 1 in {x, y, z}:
using a set to take advantage of the constant-cost membership test (in takes a fixed amount of time whatever the left-hand operand is).

When you use or, python sees each side of the operator as separate expressions. The expression x or y == 1 is treated as first a boolean test for x, then if that is False, the expression y == 1 is tested.

This is due to operator precedence. The or operator has a lower precedence than the == test, so the latter is evaluated first.

However, even if this were not the case, and the expression x or y or z == 1 was actually interpreted as (x or y or z) == 1 instead, this would still not do what you expect it to do.

x or y or z would evaluate to the first argument that is ‘truthy’, e.g. not False, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).

So for the values x = 2; y = 1; z = 0, x or y or z would resolve to 2, because that is the first true-like value in the arguments. Then 2 == 1 would be False, even though y == 1 would be True.

The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3 would fail for the same reasons. Use x == 1 or x == 2 or x == 3 or x in {1, 2, 3}.

108) Explain Python’s slice notation?

A) It’s pretty simple really:

a[start:end] # items start through end-1
a[start:] # items start through the rest of the array
a[:end] # items from the beginning through end-1
a[:] # a copy of the whole array
There is also the step value, which can be used with any of the above:

a[start:end:step] # start through not past end, by step
The key point to remember is that the :end value represents the first value that is not in the selected slice. So, the difference beween end and start is the number of elements selected (if step is 1, the default).

The other feature is that start or end may be a negative number, which means it counts from the end of the array instead of the beginning. So:

a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items

Similarly, step may be a negative number:

a[::-1] # all items in the array, reversed
a[1::-1] # the first two items, reversed
a[:-3:-1] # the last two items, reversed
a[-3::-1] # everything except the last two items, reversed

Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.

109) How to clone or copy a list in Python?

What are the options to clone or copy a list in Python?

Using new_list = my_list then modifies new_list every time my_list changes.
Why is this?

With new_list = my_list, you don’t actually have two lists. The assignment just copies the reference to the list, not the actual list, so both new_list and my_list refer to the same list after the assignment.

To actually copy the list, you have various possibilities:

You can slice it:

new_list = old_list[:]
Alex Martelli’s opinion (at least back in 2007) about this is, that it is a weird syntax and it does not make sense to use it ever. 😉 (In his opinion, the next one is more readable).

You can use the built in list() function:

new_list = list(old_list)
You can use generic copy.copy():

import copy
new_list = copy.copy(old_list)
This is a little slower than list() because it has to find out the datatype of old_list first.

If the list contains objects and you want to copy them as well, use generic copy.deepcopy():

import copy
new_list = copy.deepcopy(old_list)
Obviously the slowest and most memory-needing method, but sometimes unavoidable.

Example Program:

import copy

class Foo(object):
def __init__(self, val):
self.val = val

def __repr__(self):
return str(self.val)

foo = Foo(1)

a = [‘foo’, foo]
b = a[:]
c = list(a)
d = copy.copy(a)
e = copy.deepcopy(a)

# edit orignal list and instance
a.append(‘baz’)
foo.val = 5

print(‘original: %r\n slice: %r\n list(): %r\n copy: %r\n deepcopy: %r’
% (a, b, c, d, e))

Output:

original: [‘foo’, 5, ‘baz’]
slice: [‘foo’, 5]
list(): [‘foo’, 5]
copy: [‘foo’, 5]
deepcopy: [‘foo’, 1]

Python Interview Questions Experienced

110) List of lists changes reflected across sublists unexpectedly?

I needed to create a list of lists in Python, so I typed the following:

myList = [[1] * 4] * 3
The list looked like this:

[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
Then I changed one of the innermost values:

myList[0][0] = 5
Now my list looks like this:

[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
which is not what I wanted or expected. Can someone please explain what’s going on, and how to get around it?

A) When you write [x]*3 you get, essentially, the list [x, x, x]. That is, a list with 3 references to the same x. When you then modify this single x it is visible via all three references to it.

To fix it, you need to make sure that you create a new list at each position. One way to do it is

[[1]*4 for n in range(3)]
which will reevaluate [1]*4 each time instead of evaluating it once and making 3 references to 1 list.

Code:

size = 3
matrix_surprise = [[0] * size] * size
matrix = [[0]*size for i in range(size)]

111) How do I create a variable number of variables?

How do I accomplish variable variables in Python?

Here is an elaborative manual entry, for instance: Variable variables

I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?

A) You can use dictionaries to accomplish this. Dictionaries are stores of keys and values.

>>> dct = {‘x’: 1, ‘y’: 2, ‘z’: 3}
>>> dct
{‘y’: 2, ‘x’: 1, ‘z’: 3}
>>> dct[“y”]
2
You can use variable key names to achieve the effect of variable variables without the security risk.

>>> x = “spam”
>>> z = {x: “eggs”}
>>> z[“spam”]
‘eggs’
For cases where you’re thinking of doing something like

var1 = ‘foo’
var2 = ‘bar’
var3 = ‘baz’

a list may be more appropriate than a dict. A list represents an ordered sequence of objects, with integer indices:

l = [‘foo’, ‘bar’, ‘baz’]
print(l[1]) # prints bar, because indices start at 0
l.append(‘potatoes’) # l is now [‘foo’, ‘bar’, ‘baz’, ‘potatoes’]
For ordered sequences, lists are more convenient than dicts with integer keys, because lists support iteration in index order, slicing, append, and other operations that would require awkward key management with a dict.

112) How do you split a list into evenly sized chunks?

I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.

I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.

I was looking for something useful in itertools but I couldn’t find anything obviously useful. Might’ve missed it, though.

A) Here’s a generator that yields the chunks you want:

def chunks(l, n):
“””Yield successive n-sized chunks from l.”””
for i in range(0, len(l), n):
yield l[i:i + n]
import pprint
pprint.pprint(list(chunks(range(10, 75), 10)))
[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
[70, 71, 72, 73, 74]]

If you’re using Python 2, you should use xrange() instead of range():

def chunks(l, n):
“””Yield successive n-sized chunks from l.”””
for i in xrange(0, len(l), n):
yield l[i:i + n]
Also you can simply use list comprehension instead of writing a function. Python 3:

[l[i:i + n] for i in range(0, len(l), n)]

Python 2 version:

[l[i:i + n] for i in xrange(0, len(l), n)]

If you want something super simple:

def chunks(l, n):
n = max(1, n)
return (l[i:i+n] for i in xrange(0, len(l), n))

Python Developer Interview Questions

113) Making a flat list out of list of lists in Python?

I wonder whether there is a shortcut to make a simple list out of list of lists in Python.

I can do that in a for loop, but maybe there is some cool “one-liner”? I tried it with reduce, but I get an error.

Code:

l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)

Error message

Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
File “<stdin>”, line 1, in <lambda>
AttributeError: ‘NoneType’ object has no attribute ‘extend’

A) flat_list = [item for sublist in l for item in sublist]
which means:

for sublist in l:
for item in sublist:
flat_list.append(item)

is faster than the shortcuts posted so far. (l is the list to flatten.)

Here is a the corresponding function:

flatten = lambda l: [item for sublist in l for item in sublist]
For evidence, as always, you can use the timeit module in the standard library:

$ python -mtimeit -s’l=[[1,2,3],[4,5,6], [7], [8,9]]*99′ ‘[item for sublist in l for item in sublist]’
10000 loops, best of 3: 143 usec per loop
$ python -mtimeit -s’l=[[1,2,3],[4,5,6], [7], [8,9]]*99′ ‘sum(l, [])’
1000 loops, best of 3: 969 usec per loop
$ python -mtimeit -s’l=[[1,2,3],[4,5,6], [7], [8,9]]*99′ ‘reduce(lambda x,y: x+y,l)’
1000 loops, best of 3: 1.1 msec per loop

Explanation: the shortcuts based on + (including the implied use in sum) are, of necessity, O(L**2) when there are L sublists — as the intermediate result list keeps getting longer, at each step a new intermediate result list object gets allocated, and all the items in the previous intermediate result must be copied over (as well as a few new ones added at the end).

So (for simplicity and without actual loss of generality) say you have L sublists of I items each: the first I items are copied back and forth L-1 times, the second I items L-2 times, and so on; total number of copies is I times the sum of x for x from 1 to L excluded, i.e., I * (L**2)/2.

The list comprehension just generates one list, once, and copies each item over (from its original place of residence to the result list) also exactly once.

114) How to remove items from a list while iterating?

I’m iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.

for tup in somelist:
if determine(tup):
code_to_remove_tup

What should I use in place of code_to_remove_tup? I can’t figure out how to remove the item in this fashion.

A) You can use a list comprehension to create a new list containing only the elements you don’t want to remove:

somelist = [x for x in somelist if not determine(x)]
Or, by assigning to the slice somelist[:], you can mutate the existing list to contain only the items you want:

somelist[:] = [x for x in somelist if not determine(x)]
This approach could be useful if there are other references to somelist that need to reflect the changes.

Instead of a comprehension, you could also use itertools. In Python 2:

from itertools import ifilterfalse
somelist[:] = ifilterfalse(determine, somelist)
Or in Python 3:

from itertools import filterfalse
somelist[:] = filterfalse(determine, somelist)

115) Short Description of the Scoping Rules?

What exactly are the Python scoping rules?

If I have some code:

code1
class Foo:
code2
def spam…..
code3
for code4..:
code5
x()

Where is x found? Some possible choices include the list above:

In the enclosing source file
In the class namespace
In the function definition
In the for loop index variable
Inside the for loop
Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?

There must be a simple reference or algorithm somewhere. It’s a confusing world for intermediate Python programmers.

A) Actually, a concise rule for Python Scope resolution, from Learning Python, 3rd. Ed.. (These rules are specific to variable names, not attributes. If you reference it without a period, these rules apply)

LEGB Rule.

L, Local — Names assigned in any way within a function (def or lambda)), and not declared global in that function.

E, Enclosing-function locals — Name in the local scope of any and all statically enclosing functions (def or lambda), from inner to outer.

G, Global (module) — Names assigned at the top-level of a module file, or by executing a global statement in a def within the file.

B, Built-in (Python) — Names preassigned in the built-in names module : open,range,SyntaxError,…

So, in the case of

code1
class Foo:
code2
def spam…..
code3
for code4..:
code5
x()
The for loop does not have its own namespace. In LEGB order, the scopes would be

L : local, in def spam (in code3, code 4, code5).

E : Enclosed function, any enclosing functions (if the whole example were in another def)

G : Global. Were there any x declared globally in the module (code1)?

B : Any builtin x in Python.

x will never be found in code2 (even in cases where you might expect it would)

Python Developer Interview Questions And Answers

116) What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

In the following method definitions, what does the * and ** do for param2?

def foo(param1, *param2):
def bar(param1, **param2):

A) The *args and **kwargs is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation.

The *args will give you all function parameters as a tuple:

In [1]: def foo(*args):
…: for a in args:
…: print a
…:
…:

In [2]: foo(1)
1

In [4]: foo(1,2,3)
1
2
3

The **kwargs will give you all keyword arguments except for those corresponding to a formal parameter as a dictionary.

In [5]: def bar(**kwargs):
…: for a in kwargs:
…: print a, kwargs[a]
…:
…:

In [6]: bar(name=’one’, age=27)
age 27
name one

Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:

def foo(kind, *args, **kwargs):
pass
Another usage of the *l idiom is to unpack argument lists when calling a function.

In [9]: def foo(bar, lee):
…: print bar, lee
…:
…:

In [10]: l = [1,2]

In [11]: foo(*l)
1 2

In Python 3 it is possible to use *l on the left side of an assignment (Extended Iterable Unpacking), though it gives a list instead of a tuple in this context:

first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]

Also Python 3 adds new semantic (refer PEP 3102):

def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass
Such function accepts only 3 positional arguments, and everything after * can only be passed as keyword arguments.

117) Calling an external command in Python?

How can I call an external command (as if I’d typed it at the Unix shell or Windows command prompt) from within a Python script?

A) Look at the subprocess module in the standard library:

from subprocess import call
call([“ls”, “-l”])
The advantage of subprocess vs system is that it is more flexible (you can get the stdout, stderr, the “real” status code, better error handling, etc…).

118) What does if __name__ == “__main__”: do?

# Threading example
import time, thread

def myfunction(string, sleeptime, lock, *args):
while True:
lock.acquire()
time.sleep(sleeptime)
lock.release()
time.sleep(sleeptime)

if __name__ == “__main__”:
lock = thread.allocate_lock()
thread.start_new_thread(myfunction, (“Thread #: 1”, 2, lock))
thread.start_new_thread(myfunction, (“Thread #: 2”, 2, lock))

A) When the Python interpreter reads a source file, it executes all of the code found in it.

Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value “__main__”. If this file is being imported from another module, __name__ will be set to the module’s name.

In the case of your script, let’s assume that it’s executing as the main function, e.g. you said something like

python threading_example.py

on the command line. After setting up the special variables, it will execute the import statement and load those modules. It will then evaluate the def block, creating a function object and creating a variable called myfunction that points to the function object. It will then read the if statement and see that __name__ does equal “__main__”, so it will execute the block shown there.

One reason for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.

119) Using global variables in a function other than the one that created them.

If I create a global variable in one function, how can I use that variable in another function?

Do I need to store the global variable in a local variable of the function which needs its access?

A) You can use a global variable in other functions by declaring it as global in each function that assigns to it:

globvar = 0

def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1

def print_globvar():
print(globvar) # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar() # Prints 1
I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that’s what you’re playing with by explicitly requiring the global keyword.

See other answers if you want to share a global variable across modules.

120) How do I sort a dictionary by value?

I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.

I can sort on the keys, but how can I sort based on the values?

A) It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

For instance,

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
sorted_x will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x.

And for those wishing to sort on keys instead of values:

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))

Python Developer Interview Questions For Experienced

121) Flatten an irregular list of lists

L = [[[1, 2, 3], [4, 5]], 6]
Where the desired output is

[1, 2, 3, 4, 5, 6]
Or perhaps even better, an iterator.

def flatten(x):
result = []
for el in x:
if hasattr(el, “__iter__”) and not isinstance(el, basestring):
result.extend(flatten(el))
else:
result.append(el)
return result

flatten(L)
Is this the best model? Did I overlook something? Any problems?

A) Using generator functions can make your example a little easier to read and probably boost the performance.

Python 2
def flatten(l):
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
for sub in flatten(el):
yield sub
else:
yield el
I used the Iterable ABC added in 2.6.

Python 3
In Python 3, the basestring is no more, but you can use a tuple of str and bytes to get the same effect there.

The yield from operator returns an item from a generator one at a time. This syntax for delegating to a subgenerator was added in 3.3

def flatten(l):
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
yield from flatten(el)
else:
yield el

122) What are metaclasses and what do we use them for?

A) A metaclass is the class of a class. Like a class defines how an instance of the class behaves, a metaclass defines how a class behaves. A class is an instance of a metaclass.

While in Python you can use arbitrary callables for metaclasses (like Jerub shows), the more useful approach is actually to make it an actual class itself. type is the usual metaclass in Python. In case you’re wondering, yes, type is itself a class, and it is its own type. You won’t be able to recreate something like type purely in Python, but Python cheats a little. To create your own metaclass in Python you really just want to subclass type.

A metaclass is most commonly used as a class-factory. Like you create an instance of the class by calling the class, Python creates a new class (when it executes the ‘class’ statement) by calling the metaclass. Combined with the normal __init__ and __new__ methods, metaclasses therefore allow you to do ‘extra things’ when creating a class, like registering the new class with some registry, or even replace the class with something else entirely.

When the class statement is executed, Python first executes the body of the class statement as a normal block of code. The resulting namespace (a dict) holds the attributes of the class-to-be. The metaclass is determined by looking at the baseclasses of the class-to-be (metaclasses are inherited), at the __metaclass__ attribute of the class-to-be (if any) or the __metaclass__ global variable. The metaclass is then called with the name, bases and attributes of the class to instantiate it.

However, metaclasses actually define the type of a class, not just a factory for it, so you can do much more with them. You can, for instance, define normal methods on the metaclass.

These metaclass-methods are like classmethods, in that they can be called on the class without an instance, but they are also not like classmethods in that they cannot be called on an instance of the class. type.__subclasses__() is an example of a method on the type metaclass. You can also define the normal ‘magic’ methods, like __add__, __iter__ and __getattr__, to implement or change how the class behaves.

Here’s an aggregated example of the bits and pieces:

def make_hook(f):
“””Decorator to turn ‘foo’ method into ‘__foo__'”””
f.is_hook = 1
return f

class MyType(type):
def __new__(mcls, name, bases, attrs):

if name.startswith(‘None’):
return None

# Go over attributes and see if they should be renamed.
newattrs = {}
for attrname, attrvalue in attrs.iteritems():
if getattr(attrvalue, ‘is_hook’, 0):
newattrs[‘__%s__’ % attrname] = attrvalue
else:
newattrs[attrname] = attrvalue

return super(MyType, mcls).__new__(mcls, name, bases, newattrs)

def __init__(self, name, bases, attrs):
super(MyType, self).__init__(name, bases, attrs)

# classregistry.register(self, self.interfaces)
print “Would register class %s now.” % self

def __add__(self, other):
class AutoClass(self, other):
pass
return AutoClass
# Alternatively, to autogenerate the classname as well as the class:
# return type(self.__name__ + other.__name__, (self, other), {})

def unregister(self):
# classregistry.unregister(self)
print “Would unregister class %s now.” % self

class MyObject:
__metaclass__ = MyType

class NoneSample(MyObject):
pass

# Will print “NoneType None”
print type(NoneSample), repr(NoneSample)

class Example(MyObject):
def __init__(self, value):
self.value = value
@make_hook
def add(self, other):
return self.__class__(self.value + other.value)

# Will unregister the class
Example.unregister()

inst = Example(10)
# Will fail with an AttributeError
#inst.unregister()

print inst + inst
class Sibling(MyObject):
pass

ExampleSibling = Example + Sibling
# ExampleSibling is now a subclass of both Example and Sibling (with no
# content of its own) although it will believe it’s called ‘AutoClass’
print ExampleSibling
print ExampleSibling.__mro__

Python Experience Interview Questions

123) Why does the following behave unexpectedly in Python?

>>> a = 256
>>> b = 256
>>> a is b
True # This is an expected result
>>> a = 257
>>> b = 257
>>> a is b
False # What happened here? Why is this False?
>>> 257 is 257
True # Yet the literal numbers compare properly
I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.

Based on the above, I can hypothesize that Python is internally implemented such that “small” integers are stored in a different way than larger integers and the is operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don’t know in advance whether they are numbers or not?

A) Take a look at this:

>>> a = 256
>>> b = 256
>>> id(a)
9987148
>>> id(b)
9987148
>>> a = 257
>>> b = 257
>>> id(a)
11662816
>>> id(b)
11662828

124) Why do I receive a syntax error when printing a string in Python 3?

>>> print “hello World”
File “<stdin>”, line 1
print “hello World”
^
SyntaxError: invalid syntax

A) In Python 3, print became a function. This means that you need to include parenthesis now like mentioned below:

print(“Hello World”)

125) Does Python have a ternary conditional operator?

If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?

A) Yes, it was added in version 2.5.
The syntax is:

a if condition else b
First condition is evaluated, then either a or b is returned based on the Boolean value of condition
If condition evaluates to True a is returned, else b is returned.

For example:

>>> ‘true’ if True else ‘false’
‘true’
>>> ‘true’ if False else ‘false’
‘false’

Note that conditionals are an expression, not a statement. This means you can’t use assignments or pass or other statements in a conditional:

>>> pass if False else x = 3
File “<stdin>”, line 1
pass if False else x = 3
^
SyntaxError: invalid syntax

In such a case, you have to use a normal if statement instead of a conditional.

126) How to avoid having class data shared among instances?

What I want is this behavior:

class a:
list = []

x = a()
y = a()

x.list.append(1)
y.list.append(2)
x.list.append(3)
y.list.append(4)

print(x.list) # prints [1, 3]
print(y.list) # prints [2, 4]
Of course, what really happens when I print is:

print(x.list) # prints [1, 2, 3, 4]
print(y.list) # prints [1, 2, 3, 4]

Clearly they are sharing the data in class a. How do I get separate instances to achieve the behavior I desire?

A) You want this:

class a:
def __init__(self):
self.list = []

Declaring the variables inside the class declaration makes them “class” members and not instance members. Declaring them inside the __init__ method makes sure that a new instance of the members is created alongside every new instance of the object, which is the behavior you’re looking for.

Python Programming Interview Questions

127) How to make a chain of function decorators?

How can I make two decorators in Python that would do the following?

@makebold
@makeitalic
def say():
return “Hello”
…which should return:

“<b><i>Hello</i></b>”
I’m not trying to make HTML this way in a real application – just trying to understand how decorators and decorator chaining works.

A) Here is what you asked for:

def makebold(fn):
def wrapped():
return “<b>” + fn() + “</b>”
return wrapped

def makeitalic(fn):
def wrapped():
return “<i>” + fn() + “</i>”
return wrapped

@makebold
@makeitalic
def hello():
return “hello world”

print hello() ## returns “<b><i>hello world</i></b>”

128) Is there any way to kill a Thread in Python?

Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?

A) There is no official API to do that, no.

You need to use platform API to kill the thread, e.g. pthread_kill, or TerminateThread. You can access such API e.g. through pythonwin, or through ctypes.

Notice that this is inherently unsafe. It will likely lead to uncollectable garbage (from local variables of the stack frames that become garbage), and may lead to deadlocks, if the thread being killed has the GIL at the point when it is killed.

129) Difference between __str__ and __repr__?

What is the difference between __str__ and __repr__ in Python?

A) My rule of thumb: __repr__ is for developers, __str__ is for customers.

130) Why is Button parameter “command” executed when declared?

My code is:

from Tkinter import *

admin = Tk()
def button(an):
print an
print ‘het’

b = Button(admin, text=’as’, command=button(‘hey’))
b.pack()
mainloop()

The button doesn’t work, it prints ‘hey’ and ‘het’ once without my command, and then, when I press the button nothing happens.

A) You need to create a function without parameters that you can use as the command:

b = Button(admin, text=’as’, command=lambda: button(‘hey’))

Advanced Python Programming Interview Questions

131) Why is using ‘eval’ a bad practice?

I am using the following class to easily store data of my songs.

class Song:
“””The class to store the details of each song”””
attsToStore=(‘Name’, ‘Artist’, ‘Album’, ‘Genre’, ‘Location’)
def __init__(self):
for att in self.attsToStore:
exec ‘self.%s=None’%(att.lower()) in locals()
def setDetail(self, key, val):
if key in self.attsToStore:
exec ‘self.%s=val’%(key.lower()) in locals()

I feel that this is just much more extensible than writing out an if/else block. However, eval seems to be considered a bad practice and unsafe to use. If so, can anyone explain to me why and show me a better way of defining the above class?

A) Yes, using eval is a bad practice. Just to name a few reasons:

There is almost always a better way to do it
Very dangerous and insecure
Makes debugging difficult
Slow
In your case you can use setattr instead:

class Song:
“””The class to store the details of each song”””
attsToStore=(‘Name’, ‘Artist’, ‘Album’, ‘Genre’, ‘Location’)
def __init__(self):
for att in self.attsToStore:
setattr(self, att.lower(), None)
def setDetail(self, key, val):
if key in self.attsToStore:
setattr(self, key.lower(), val)

There are some cases where you have to use eval or exec. But they are rare. Using eval in your case is a bad practice for sure. I’m emphasizing on bad practice because eval and exec are frequently used in the wrong place.

It looks like some disagree that eval is ‘very dangerous and insecure’ in the OP case. That might be true for this specific case but not in general. The question was general and the reasons I listed are true for the general case as well.

132) What is the purpose of self?

What is the purpose of the self word in Python? I understand it refers to the specific object created from that class, but I can’t see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this:

class myClass
def myFunc(name)
@name = name
end
end

Which I understand, quite easily. However in Python I need to include self:

class myClass:
def myFunc(self, name):
self.name = name

Can anyone talk me through this? It is not something I’ve come across in my (admittedly limited) experience.

A) The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on.

That makes methods entirely the same as functions, and leaves the actual name to use up to you (although self is the convention, and people will generally frown at you when you use something else.) self is not special to the code, it’s just another object.

Python could have done something else to distinguish normal names from attributes — special syntax like Ruby has, or requiring declarations like C++ and Java do, or perhaps something yet more different — but it didn’t. Python’s all for making things explicit, making it obvious what’s what, and although it doesn’t do it entirely everywhere, it does do it for instance attributes. That’s why assigning to an instance attribute needs to know what instance to assign to, and that’s why it needs self.

133) How do you remove duplicates from a list whilst preserving order?

Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:

def uniq(input):
output = []
for x in input:
if x not in output:
output.append(x)
return output

A) Fastest one:

def f7(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]

Why assign seen.add to seen_add instead of just calling seen.add? Python is a dynamic language, and resolving seen.add each iteration is more costly than resolving a local variable. seen.add could have changed between iterations, and the runtime isn’t smart enough to rule that out. To play it safe, it has to check the object each time.

134) What is the meaning of a single- and a double-underscore before an object name?

I want to clear this up once and for all. Can someone please explain the exact meaning of having leading underscores before an object’s name in Python? Also explain the difference between a single and a double leading underscore. Also, does that meaning stay the same whether the object in question is a variable, a function, a method, etc?

A) Single Underscore – Names, in a class, with a leading underscore are simply to indicate to other programmers that the attribute or method is intended to be private. However, nothing special is done with the name itself.

Double Underscore (Name Mangling) – Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.

Example:

>>> class MyClass():
… def __init__(self):
… self.__superprivate = “Hello”
… self._semiprivate = “, world!”

>>> mc = MyClass()
>>> print mc.__superprivate
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
AttributeError: myClass instance has no attribute ‘__superprivate’
>>> print mc._semiprivate
, world!
>>> print mc.__dict__
{‘_MyClass__superprivate’: ‘Hello’, ‘_semiprivate’: ‘, world!’}

Python Programming Interview Questions And Answers

135) Converting string into datetime

Short and simple. I’ve got a huge list of date-times like this as strings:

Jun 1 2005 1:33PM
Aug 28 1999 12:00AM

I’m going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.

Any help (even if it’s just a kick in the right direction) would be appreciated.

A) datetime.strptime is the main routine for parsing strings into datetimes. It can handle all sorts of formats, with the format determined by a format string you give it:

from datetime import datetime

datetime_object = datetime.strptime(‘Jun 1 2005 1:33PM’, ‘%b %d %Y %I:%M%p’)

The resulting datetime object is timezone-naive.

Links:

Python documentation for strptime: Python 2, Python 3

Python documentation for strptime/strftime format strings: Python 2, Python 3

strftime.org is also a really nice reference for strftime

Notes:

strptime = “string parse time”
strftime = “string format time”
Pronounce it out loud today & you won’t have to search for it again in 6 months.

136) Why does comparing strings in Python using either ‘==’ or ‘is’ sometimes produce a different result?

I’ve got a Python program where two variables are set to the value ‘public’. In a conditional expression I have the comparison var1 is var2 which fails, but if I change it to var1 == var2 it returns True.

Now if I open my Python interpreter and do the same “is” comparison, it succeeds.

>>> s1 = ‘public’
>>> s2 = ‘public’
>>> s2 is s1
True
What am I missing here?

A) is is identity testing, == is equality testing. what happens in your code would be emulated in the interpreter like this:

>>> a = ‘pub’
>>> b = ”.join([‘p’, ‘u’, ‘b’])
>>> a == b
True
>>> a is b
False
so, no wonder they’re not the same, right?

In other words: is is the id(a) == id(b)

137) How to iterate through two lists in parallel?

I have two iterables in Python, and I want to go over them in pairs:

foo = (1, 2, 3)
bar = (4, 5, 6)

for (f, b) in some_iterator(foo, bar):
print “f: “, f, “; b: “, b

It should result in:

f: 1; b: 4
f: 2; b: 5
f: 3; b: 6
One way to do it is to iterate over the indices:

for i in xrange(len(foo)):
print “f: “, foo[i], “; b: “, b[i]

But that seems somewhat unpythonic to me. Is there a better way to do it?

A) for f, b in zip(foo, bar):
print(f, b)
zip stops when the shorter of foo or bar stops.

In Python 2, zip returns a list of tuples. This is fine when foo and bar are not massive. If they are both massive then forming zip(foo,bar) is an unnecessarily massive temporary variable, and should be replaced by itertools.izip or itertools.izip_longest, which returns an iterator instead of a list.

import itertools
for f,b in itertools.izip(foo,bar):
print(f,b)
for f,b in itertools.izip_longest(foo,bar):
print(f,b)
izip stops when either foo or bar is exhausted. izip_longest stops when both foo and bar are exhausted. When the shorter iterator(s) are exhausted, izip_longest yields a tuple with None in the position corresponding to that iterator. You can also set a different fillvalue besides None if you wish. See here for the full story.

In Python 3, zip returns an iterator of tuples, like itertools.izip in Python2. To get a list of tuples, use list(zip(foo, bar)). And to zip until both iterators are exhausted, you would use itertools.zip_longest.

Note also that zip and its zip-like brethen can accept an arbitrary number of iterables as arguments. For example,

for num, cheese, color in zip([1,2,3], [‘manchego’, ‘stilton’, ‘brie’],
[‘red’, ‘blue’, ‘green’]):
print(‘{} {} {}’.format(num, color, cheese))

prints

1 red manchego
2 blue stilton
3 green brie

Python Scripting Interview Questions

138) How to merge two dictionaries in a single expression?

A) I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The update() method would be what I need, if it returned its result instead of modifying a dict in-place.

>>> x = {‘a’:1, ‘b’: 2}
>>> y = {‘b’:10, ‘c’: 11}
>>> z = x.update(y)
>>> print(z)
None
>>> x
{‘a’: 1, ‘b’: 10, ‘c’: 11}

How can I get that final merged dict in z, not x?

(To be extra-clear, the last-one-wins conflict-handling of dict.update() is what I’m looking for as well.)

A) For dictionaries x and y, z becomes a merged dictionary with values from y replacing those from x.

In Python 3.5 or greater, :

z = {**x, **y}
In Python 2, (or 3.4 or lower) write a function:

def merge_two_dicts(x, y):
z = x.copy() # start with x’s keys and values
z.update(y) # modifies z with y’s keys and values & returns None
return z
and

z = merge_two_dicts(x, y)

Explanation:

Say you have two dicts and you want to merge them into a new dict without altering the original dicts:

x = {‘a’: 1, ‘b’: 2}
y = {‘b’: 3, ‘c’: 4}

The desired result is to get a new dictionary (z) with the values merged, and the second dict’s values overwriting those from the first.

>>> z
{‘a’: 1, ‘b’: 3, ‘c’: 4}

A new syntax for this, proposed in PEP 448 and available as of Python 3.5, is

z = {**x, **y}

And it is indeed a single expression. It is now showing as implemented in the release schedule for 3.5, PEP 478, and it has now made its way into What’s New in Python 3.5 document.

However, since many organizations are still on Python 2, you may wish to do this in a backwards compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process:

z = x.copy()
z.update(y) # which returns None since it mutates z
In both approaches, y will come second and its values will replace x’s values, thus ‘b’ will point to 3 in our final result.

139) In Python, how do I read a file line-by-line into a list?

How do I read every line of a file in Python and store each line as an element in a list?

I want to read the file line by line and append each line to the end of the list.

A) with open(fname) as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]

I’m guessing that you meant list and not array.

Python Scripting Interview Questions And Answers

140) How to print without newline or space?

I’d like to do it in python. What I’d like to do in this example in c:

#include <stdio.h>

int main() {
int i;
for (i=0; i<10; i++) printf(“.”);
return 0;
}
Output:

……….
In Python:

>>> for i in xrange(0,10): print ‘.’
.
.
.
.
.
.
.
.
.
.
>>> for i in xrange(0,10): print ‘.’,
. . . . . . . . . .
In Python print will add a \n or a space, how can I avoid that? Now, it’s just an example. Don’t tell me I can first build a string then print it. I’d like to know how to “append” strings to stdout.

A) General way

import sys
sys.stdout.write(‘.’)
You may also need to call

sys.stdout.flush()
to ensure stdout is flushed immediately.

Python 2.6+

From Python 2.6 you can import the print function from Python 3:

from __future__ import print_function
This allows you to use the Python 3 solution below.

Python 3

In Python 3, the print statement has been changed into a function. In Python 3, you can instead do:

print(‘.’, end=”)
This also works in Python 2, provided that you’ve used from __future__ import print_function.

If you are having trouble with buffering, you can flush the output by adding flush=True keyword argument:

print(‘.’, end=”, flush=True)

141) Get the cartesian product of a series of lists?

How can I get the Cartesian product (every possible combination of values) from a group of lists?

Input:

somelists = [
[1, 2, 3],
[‘a’, ‘b’],
[4, 5]
]
Desired output:

[(1, ‘a’, 4), (1, ‘a’, 5), (1, ‘b’, 4), (1, ‘b’, 5), (2, ‘a’, 4), (2, ‘a’, 5) …]

A) In Python 2.6+

import itertools
for element in itertools.product(*somelists):
print(element)

142) Does Python have a built in function for string natural sort?

Using Python 3.x, I have a list of strings for which I would like to perform a natural alphabetical sort.

Natural sort: The order by which files in Windows are sorted.

For instance, the following list is naturally sorted (what I want):

[‘elm0’, ‘elm1’, ‘Elm2’, ‘elm9’, ‘elm10’, ‘Elm11’, ‘Elm12’, ‘elm13’]

And here’s the “sorted” version of the above list (what I have):

[‘Elm11’, ‘Elm12’, ‘Elm2’, ‘elm0’, ‘elm1’, ‘elm10’, ‘elm13’, ‘elm9’]

I’m looking for a sort function which behaves like the first one.

A) There is a third party library for this on PyPI called natsort (full disclosure, I am the package’s author). For your case, you can do either of the following:

>>> from natsort import natsorted, ns
>>> x = [‘Elm11’, ‘Elm12’, ‘Elm2’, ‘elm0’, ‘elm1’, ‘elm10’, ‘elm13’, ‘elm9’]
>>> natsorted(x, key=lambda y: y.lower())
[‘elm0’, ‘elm1’, ‘Elm2’, ‘elm9’, ‘elm10’, ‘Elm11’, ‘Elm12’, ‘elm13’]
>>> natsorted(x, alg=ns.IGNORECASE) # or alg=ns.IC
[‘elm0’, ‘elm1’, ‘Elm2’, ‘elm9’, ‘elm10’, ‘Elm11’, ‘Elm12’, ‘elm13’]
You should note that natsort uses a general algorithm so it should work for just about any input that you throw at it. If you want more details on why you might choose a library to do this rather than rolling your own function, check out the natsort documentation’s How It Works page, in particular the Special Cases Everywhere! section.

If you need a sorting key instead of a sorting function, use either of the below formulas.

>>> from natsort import natsort_keygen, ns
>>> l1 = [‘elm0’, ‘elm1’, ‘Elm2’, ‘elm9’, ‘elm10’, ‘Elm11’, ‘Elm12’, ‘elm13’]
>>> l2 = l1[:]
>>> natsort_key1 = natsort_keygen(key=lambda y: y.lower())
>>> l1.sort(key=natsort_key1)
>>> l1
[‘elm0’, ‘elm1’, ‘Elm2’, ‘elm9’, ‘elm10’, ‘Elm11’, ‘Elm12’, ‘elm13’]
>>> natsort_key2 = natsort_keygen(alg=ns.IGNORECASE)
>>> l2.sort(key=natsort_key2)
>>> l2
[‘elm0’, ‘elm1’, ‘Elm2’, ‘elm9’, ‘elm10’, ‘Elm11’, ‘Elm12’, ‘elm13’]

Python Coding Interview Questions

143) Convert a string representation of list to list.

I was wondering what the simplest way is to convert a string list like the following to a list:

x = u'[ “A”,”B”,”C” , ” D”]’

Even in case user puts spaces in between the commas, and spaces inside of the quotes. I need to handle that as well to:

x = [“A”, “B”, “C”, “D”]

in Python.

I know I can strip spaces with strip() and split() using the split operator and check for non alphabets. But the code was getting very kludgy. Is there a quick function that I’m not aware of?

A) >>> import ast
>>> x = u'[ “A”,”B”,”C” , ” D”]’
>>> x = ast.literal_eval(x)
>>> x
[‘A’, ‘B’, ‘C’, ‘ D’]
>>> x = [n.strip() for n in x]
>>> x
[‘A’, ‘B’, ‘C’, ‘D’]

ast.literal_eval:

With ast.literal_eval, you can safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

144) How to import a module given the full path?

How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.

A) For Python 3.5+ use:

import importlib.util
spec = importlib.util.spec_from_file_location(“module.name”, “/path/to/file.py”)
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.MyClass()

For Python 3.3 and 3.4 use:

from importlib.machinery import SourceFileLoader

foo = SourceFileLoader(“module.name”, “/path/to/file.py”).load_module()
foo.MyClass()

(Although this has been deprecated in Python 3.4.)

Python 2 use:

import imp

foo = imp.load_source(‘module.name’, ‘/path/to/file.py’)
foo.MyClass()

There are equivalent convenience functions for compiled Python files and DLLs.

145) Is there a difference between `==` and `is` in Python?

A) In Python, are the following two tests for equality equivalent?

n = 5
# Test one.
if n == 5:
print ‘Yay!’

# Test two.
if n is 5:
print ‘Yay!’
Does this hold true for objects where you would be comparing instances (a list say)?

Okay, so this kind of answers my question:

L = []
L.append(1)
if L == [1]:
print ‘Yay!’
# Holds true, but…

if L is [1]:
print ‘Yay!’
# Doesn’t.

So == tests value where is tests to see if they are the same object?

A) is will return True if two variables point to the same object, == if the objects referred to by the variables are equal.

>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
>>> b == a
True
>>> b = a[:]
>>> b is a
False
>>> b == a
True

In your case, the second test only works because Python caches small integer objects, which is an implementation detail. For larger integers, this does not work:

>>> 1000 is 10**3
False
>>> 1000 == 10**3
True
The same holds true for string literals:

>>> “a” is “a”
True
>>> “aa” is “a” * 2
True
>>> x = “a”
>>> “aa” is x * 2
False
>>> “aa” is intern(x*2)
True

Python Coding Interview Questions And Answers

146) What’s the difference between raw_input() and input() in python3.x?

What is the difference between raw_input() and input() in python3.x ?

A) The difference is that raw_input() does not exist in Python 3.x, while input() does. Actually, the old raw_input() has been renamed to input(), and the old input() is gone, but can easily be simulated by using eval(input()). (Remember that eval() is evil, so if try to use safer ways of parsing your input if possible.)

147) What is the difference between old style and new style classes in Python?

What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days?

A) Up to Python 2.1, old-style classes were the only flavour available to the user. The concept of (old-style) class is unrelated to the concept of type: if x is an instance of an old-style class, then x.__class__ designates the class of x, but type(x) is always <type ‘instance’>. This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called instance.

New-style classes were introduced in Python 2.2 to unify the concepts of class and type. A new-style class is simply a user-defined type, no more, no less. If x is an instance of a new-style class, then type(x) is typically the same as x.__class__ (although this is not guaranteed – a new-style class instance is permitted to override the value returned for x.__class__).

The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model. It also has a number of immediate benefits, like the ability to subclass most built-in types, or the introduction of “descriptors”, which enable computed properties.

For compatibility reasons, classes are still old-style by default. New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the “top-level type” object if no other parent is needed. The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type returns.

Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are “fixes” that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance.

Python 3 only has new-style classes. No matter if you subclass from object or not, classes are new-style in Python 3.

148) Understanding Python super() with __init__() methods?

I’m trying to understand the use of super(). From the looks of it, both child classes can be created, just fine.

I’m curious to know about the actual difference between the following 2 child classes.

class Base(object):
def __init__(self):
print “Base created”

class ChildA(Base):
def __init__(self):
Base.__init__(self)

class ChildB(Base):
def __init__(self):
super(ChildB, self).__init__()

ChildA()
ChildB()

A) super() lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen. See the standard docs on super if you haven’t already.

Note that the syntax changed in Python 3.0: you can just say super().__init__() instead of super(ChildB, self).__init__() which IMO is quite a bit nicer.

149) How do you append to a file?

How do you append to the file instead of overwriting it? Is there a special function that appends to the file?

A) with open(“test.txt”, “a”) as myfile:
myfile.write(“appended text”)

150) How to count the occurrences of a list item?

Given an item, how can I count its occurrences in a list in Python?

A) If you only want one item’s count, use the count method:

>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3

Don’t use this if you want to count multiple items. Calling count in a loop requires a separate pass over the list for every count call, which can be catastrophic for performance. If you want to count all items, or even just multiple items, use Counter, as explained in the other answers.

Python Programming Questions

151) Python variable scope error.

The following code works as expected in both Python 2.5 and 3.0:

a, b, c = (1, 2, 3)

print(a, b, c)

def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()

However, when I uncomment line (B), I get an UnboundLocalError: ‘c’ not assigned at line (A). The values of a and b are printed correctly. This has me completely baffled for two reasons:

Why is there a runtime error thrown at line (A) because of a later statement on line (B)?

Why are variables a and b printed as expected, while c raises an error?

The only explanation I can come up with is that a local variable c is created by the assignment c+=1, which takes precedent over the “global” variable c even before the local variable is created. Of course, it doesn’t make sense for a variable to “steal” scope before it exists.

Could someone please explain this behavior?

A) Python treats variables in functions differently depending on whether you assign values to them from within the function or not. If a function contains any assignments to a variable, it is treated by default as a local variable. Therefore, when you uncomment the line, you are trying to reference a local variable before any value has been assigned to it.

If you want the variable c to refer to the global c put

global c

as the first line of the function.

As for python 3, there is now

nonlocal c

that you can use to refer to the nearest enclosing function scope that has a c variable.

152) Python List Comprehension Vs. Map

Is there a reason to prefer using map() over list comprehension or vice versa? Is either of them generally more efficient or considered generally more pythonic than the other?

A) map may be microscopically faster in some cases (when you’re NOT making a lambda for the purpose, but using the same function in map and a listcomp). List comprehensions may be faster in other cases and most (not all) pythonistas consider them more direct and clearer.

An example of the tiny speed advantage of map when using exactly the same function:

$ python -mtimeit -s’xs=range(10)’ ‘map(hex, xs)’
100000 loops, best of 3: 4.86 usec per loop
$ python -mtimeit -s’xs=range(10)’ ‘[hex(x) for x in xs]’
100000 loops, best of 3: 5.58 usec per loop
An example of how performance comparison gets completely reversed when map needs a lambda:

$ python -mtimeit -s’xs=range(10)’ ‘map(lambda x: x+2, xs)’
100000 loops, best of 3: 4.24 usec per loop
$ python -mtimeit -s’xs=range(10)’ ‘[x+2 for x in xs]’
100000 loops, best of 3: 2.32 usec per loop

Python3 Interview Questions And Answers

153) UnboundLocalError in Python

What am I doing wrong here?

counter = 0

def increment():
counter += 1

increment()
The above code throws a UnboundLocalError.

A) Python doesn’t have variable declarations, so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local.[1] Thus, the line

counter += 1

implicitly makes counter local to increment(). Trying to execute this line, though, will try to read the value of the local variable counter before it is assigned, resulting in an UnboundLocalError.[2]

If counter is a global variable, the global keyword will help. If increment() is a local function and counter a local variable, you can use nonlocal in Python 3.x.

154) What is the difference between re.search and re.match?

What is the difference between the search() and match() functions in the Python re module?

A) re.match is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using ^ in the pattern.

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match.

Note: If you want to locate a match anywhere in string, use search() instead.

Scan through string looking for a location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

So if you need to match at the beginning of the string, or to match the entire string use match. It is faster. Otherwise use search.

The documentation has a specific section for match vs. search that also covers multiline strings:

Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default).

Note that match may differ from search even when using a regular expression beginning with ‘^’: ‘^’ matches only at the start of the string, or in MULTILINE mode also immediately following a newline. The “match” operation succeeds only if the pattern matches at the start of the string regardless of mode, or at the starting position given by the optional pos argument regardless of whether a newline precedes it.

Now, enough talk. Time to see some example code:

# example code:

string_with_newlines = “””something
someotherthing”””

import re

print re.match(‘some’, string_with_newlines) # matches
print re.match(‘someother’,
string_with_newlines) # won’t match
print re.match(‘^someother’, string_with_newlines,
re.MULTILINE) # also won’t match
print re.search(‘someother’,
string_with_newlines) # finds something
print re.search(‘^someother’, string_with_newlines,
re.MULTILINE) # also finds something

m = re.compile(‘thing$’, re.MULTILINE)

print m.match(string_with_newlines) # no match
print m.match(string_with_newlines, pos=4) # matches
print m.search(string_with_newlines,
re.MULTILINE) # also matches

Python Programming Interview Questions And Answers

155) How do I parse XML in Python?

I have many rows in a database that contains xml and I’m trying to write a Python script that will go through those rows and count how many instances of a particular node attribute show up. For instance, my tree looks like:

<foo>
<bar>
<type foobar=”1″/>
<type foobar=”2″/>
</bar>
</foo>

How can I access the attributes 1 and 2 in the XML using Python?

A) I suggest ElementTree. There are other compatible implementations of the same API, such as lxml, and cElementTree in the Python standard library itself; but, in this context, what they chiefly add is even more speed — the ease of programming part depends on the API, which ElementTree defines.

After building an Element instance e from the XML, e.g. with the XML function, or by parsing a file with something like

import xml.etree.ElementTree
e = xml.etree.ElementTree.parse(‘thefile.xml’).getroot()
or any of the many other ways shown at ElementTree, you just do something like:

for atype in e.findall(‘type’):
print(atype.get(‘foobar’))

and similar, usually pretty simple, code patterns.

156) What is __init__.py for?

What is __init__.py for in a Python source directory?

A) The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later (deeper) on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

157) Replacements for switch statement in Python?

I want to write a function in Python that returns different fixed values based on the value of an input index.

In other languages I would use a switch or case statement, but Python does not appear to have a switch statement. What are the recommended Python solutions in this scenario?

A) You could use a dictionary:

def f(x):
return {
‘a’: 1,
‘b’: 2,
}[x]

Python Programmer Interview Questions

158) Parsing values from a JSON file?

I have this JSON in a file:

{
“maps”: [
{
“id”: “blabla”,
“iscategorical”: “0”
},
{
“id”: “blabla”,
“iscategorical”: “0”
}
],
“masks”: [
“id”: “valore”
],
“om_points”: “value”,
“parameters”: [
“id”: “valore”
]
}

I wrote this script which prints all of the json text:

json_data=open(file_directory).read()

data = json.loads(json_data)
pprint(data)

How can I parse the file and extract single values?

A) I think what Ignacio is saying is that your JSON file is incorrect. You have [] when you should have {}. [] are for lists, {} are for dictionaries.

Here’s how your JSON file should look, your JSON file wouldn’t even load for me:

{
“maps”: [
{
“id”: “blabla”,
“iscategorical”: “0”
},
{
“id”: “blabla”,
“iscategorical”: “0”
}
],
“masks”: {
“id”: “valore”
},
“om_points”: “value”,
“parameters”: {
“id”: “valore”
}
}
Then you can use your code:

import json
from pprint import pprint

with open(‘data.json’) as f:
data = json.load(f)

pprint(data)
With data, you can now also find values like so:

data[“maps”][0][“id”]
data[“masks”][“id”]
data[“om_points”]

Try those out and see if it starts to make sense.

159) What is the purpose of the single underscore “_” variable in Python?

What is the meaning of _ after for in this code?

if tbh.bag:
n = 0
for _ in tbh.bag.atom_set():
n += 1

A) _ has 3 main conventional uses in Python:

To hold the result of the last executed expression(/statement) in an interactive interpreter session. This precedent was set by the standard CPython interpreter, and other interpreters have followed suit

For translation lookup in i18n (see the gettext documentation for example), as in code like: raise forms.ValidationError(_(“Please enter a correct username”))

As a general purpose “throwaway” variable name to indicate that part of a function result is being deliberately ignored, as in code like: label, has_label, _ = text.partition(‘:’)

The latter two purposes can conflict, so it is necessary to avoid using _ as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore, __, as their throwaway variable for exactly this reason).

Python Programming Questions And Answers

160) Reverse a string in Python

There is no built in reverse function for Python’s str object. What is the best way of implementing this method?

If supplying a very concise answer, please elaborate on its efficiency. For example, whether the str object is converted to a different object, etc.

A) How about:

>>> ‘hello world'[::-1]
‘dlrow olleh’

This is extended slice syntax. It works by doing [begin:end:step] – by leaving begin and end off and specifying a step of -1, it reverses a string.

161) How do I protect Python code?

I am developing a piece of software in Python that will be distributed to my employer’s customers. My employer wants to limit the usage of the software with a time restricted license file.

If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.

Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the “novel ideas”.

Is there a good way to handle this problem? Preferably with an off-the-shelf solution.

The software will run on Linux systems (so I don’t think py2exe will do the trick).

A) Python, being a byte-code-compiled interpreted language, is very difficult to lock down. Even if you use a exe-packager like py2exe, the layout of the executable is well-known, and the Python byte-codes are well understood.

Usually in cases like this, you have to make a tradeoff. How important is it really to protect the code? Are there real secrets in there (such as a key for symmetric encryption of bank transfers), or are you just being paranoid? Choose the language that lets you develop the best product quickest, and be realistic about how valuable your novel ideas are.

If you decide you really need to enforce the license check securely, write it as a small C extension so that the license check code can be extra-hard (but not impossible!) to reverse engineer, and leave the bulk of your code in Python.

Complex Python Interview Questions

162) How to split a string into a list?

I want my python function to split a sentence (input) and store each word in a list. The code that I’ve written so far splits the sentence, but does not store the words as a list. How do I do that?

def split_line(text):

# split the text
words = text.split()

# for each word in the line:
for word in words:

# print the word
print(word)

A) text.split()

This should be enough to store each word in a list. words is already a list of the words from the sentence, so there is no need for the loop.

Second, it might be a typo, but you have your loop a little messed up. If you really did want to use append, it would be:

words.append(word)
not

word.append(words)

163) What does “list comprehension” mean? How does it work and how can I use it?

A) List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

164) Difference between append vs. extend list methods in Python

What is the difference between the list methods append() and extend()?

A) append adds an element to a list, extend concatenates the first list with another list (or another iterable, not necessarily a list.)

append: Appends object at end.

x = [1, 2, 3]
x.append([4, 5])
print (x)

gives you: [1, 2, 3, [4, 5]]

extend: Extends list by appending elements from the iterable.

x = [1, 2, 3]
x.extend([4, 5])
print (x)

gives you: [1, 2, 3, 4, 5]

165) What exactly are iterator, iterable, and iteration?

What are the most basic definitions of “iterable”, “iterator” and “iteration in Python?

A) Iteration is a general term for taking each item of something, one after another. Any time you use a loop, explicit or implicit, to go over a group of items, that is iteration.

In Python, iterable and iterator have specific meanings.

An iterable is an object that has an __iter__ method which returns an iterator, or which defines a __getitem__ method that can take sequential indexes starting from zero (and raises an IndexError when the indexes are no longer valid). So an iterable is an object that you can get an iterator from.

An iterator is an object with a next (Python 2) or __next__ (Python 3) method.

Whenever you use a for loop, or map, or a list comprehension, etc. in Python, the next method is called automatically to get each item from the iterator, thus going through the process of iteration.

200+ Python Tutorials With Coding Examples

Python Language Basics TutorialPython String Representations of Class Instances
Python For Beginners TutorialPython Debugging Tutorial
Python Data Types TutorialReading and Writing CSV File Using Python
Python Indentation TutorialWriting to CSV in Python from String/List
Python Comments and Documentation TutorialPython Dynamic Code Execution Tutorial
Python Date And Time TutorialPython Code Distributing using Pyinstaller
Python Date Formatting TutorialPython Data Visualization Tutorial
Python Enum TutorialPython Interpreter Tutorial
Python Set TutorialPython Args and Kwargs
Python Mathematical Operators TutorialPython Garbage Collection Tutorial
Python Bitwise Operators TutorialPython Pickle Data Serialisation
Python Bolean Operators TutorialPython Binary Data Tutorial
Python Operator Precedance TutorialPython Idioms Tutorial
Python Variable Scope And Binding TutorialPython Data Serialization Tutorial
Python Conditionals TutorialPython Multiprocessing Tutorial
Python Comparisons TutorialPython Multithreading Tutorial
Python Loops TutorialPython Processes and Threads
Python Arrays TutorialPython Concurrency Tutorial
Python Multidimensional Arrays TutorialPython Parallel Computation Tutorial
Python List TutorialPython Sockets Module Tutorial
Python List Comprehensions TutorialPython Websockets Tutorial
Python List Slicing TutorialSockets Encryption Decryption in Python
Python Grouby() TutorialPython Networking Tutorial
Python Linked Lists TutorialPython http Server Tutorial
Linked List Node TutorialPython Flask Tutorial
Python Filter TutorialIntroduction to Rabbitmq using Amqpstorm Python
Python Heapq TutorialPython Descriptor Tutorial
Python Tuple TutorialPython Tempflile Tutorial
Python Basic Input And Output TutorialInput Subset and Output External Data Files using Pandas in Python
Python Files And Folders I/O TutorialUnzipping Files in Python Tutorial
Python os.path TutorialWorking with Zip Archives in Python
Python Iterables And Iterators Tutorialgzip in Python Tutorial
Python Functions TutorialStack in Python Tutorial
Defining Functions With List Arguments In PythonWorking with Global Interpreter Lock (GIL)
Functional Programming In PythonPython Deployment Tutorial
Partial Functions In PythonPython Logging Tutorial
Decorators Function In PythonPython Server Sent Events Tutorial
Python Classes TutorialPython Web Server Gateway Interface (WSGI)
Python Metaclasses TutorialPython Alternatives to Switch Statement
Python String Formatting TutorialPython Packing and Unpacking Tutorial
Python String Methods TutorialAccessing Python Sourcecode and Bytecode
Using Loops Within Functions In PythonPython Mixins Tutorial
Python Importing Modules TutorialPython Attribute Access Tutorial
Difference Betweeb Module And Package In PythonPython Arcpy Tutorial
Python Math Module TutorialPython Abstract Base Class Tutorial
Python Complex Math TutorialPython Plugin and Extension Classes
Python Collections Module TutorialPython Immutable Datatypes Tutorial
Python Operator Module TutorialPython Incompatibilities Moving from Python 2 to Python 3
Python JSON Module TutorialPython 2to3 Tool Tutorial
Python Sqlite3 Module TutorialNon-Official Python implementations
Python os Module TutorialPython Abstract Syntax Tree
Python Locale Module TutorialPython Unicode and Bytes
Python Itertools Module TutorialPython Serial Communication (pyserial)
Python Asyncio Module TutorialNeo4j and Cypher using Py2Neo
Python Random Module TutorialBasic Curses with Python
Python Functools Module TutorialTemplates in Python
Python dis Module TutorialPython Pillow
Python Base64 Module TutorialPython CLI subcommands with precise help output
Python Queue Module TutorialPython Database Access
Python Deque Module TutorialConnecting Python to SQL Server
Python Webbrowser Module TutorialPython and Excel
Python tkinter TutorialPython Turtle Graphics
Python pyautogui Module TutorialPython Persistence
Python Indexing And Slicing TutorialPython Design Patterns
Python Plotting With Matplotlib TutorialPython hashlib
Python Graph Tool TutorialCreating a Windows Service Using Python
Python Generators TutorialMutable vs Immutable (and Hashable) in Python
Python Reduce TutorialPython configparser
Python Map Function TutorialPython Optical Character Recognition
Python Exponentiation TutorialPython Virtual Environments
Python Searching TutorialPython Virtual Environment – virtualenv
Sorting Minimum And Maximum In PythonPython Virtual environment with virtualenvwrapper
Python Print Function TutorialCreate virtual environment with virtualenvwrapper in windows
Python Regular Expressions Regex TutorialPython sys Tutorial
Copying Data In Python TutorialChemPy – Python package
Python Context Managers (“with” Statement) TutorialPython pygame
Python Name Special Variable TutorialPython pyglet
Checking Path Existence And Permissions In PythonWorking with Audio in Python
Creating Python Packages TutorialPython pyaudio
Usage of pip Module In Python TutorialPython shelve
Python PyPi Package Manager TutorialIoT Programming with Python and Raspberry PI
Parsing Command Line Arguments In Pythonkivy – Cross-platform Python Framework for NUI Development
Python Subprocess Library TutorialPandas Transform
Python setup.py TutorialPython vs. JavaScript
Python Recursion TutorialCall Python from C#
Python Type Hints TutorialPython Writing Extensions
Python Exceptions TutorialPython Lex-Yacc
Raise Custom Exceptions In PythonPython Unit Testing
Python Commonwealth Exceptions TutorialPython py.test
Python urllib TutorialPython Profiling
Web Scraping With Python TutorialPython Speed of Program
Python HTML Parsing TutorialPython Performance Optimization
Manipulating XML In PythonPython Security and Cryptography
Python Requests Post TutorialSecure Shell Connection in Python
Python Distribution TutorialPython Anti Patterns
Python Property Objects TutorialPython Common Pitfalls
Python Overloading TutorialPython Hidden Features
Python Polymorphism TutorialPython For Machine Learning
Python Method Overriding TutorialPython Interview Questions And Answers For Experienced
Python User Defined Methods TutorialPython Coding Interview Questions And Answers
Python Programming Tutorials With Examples

Related Python Tutorials

RELATED INTERVIEW QUESTIONS AND ANSWERS

  1. Peoplesoft Integration Broker Interview Questions
  2. PeopleSoft Application Engine Interview Questions
  3. RSA enVision Interview Questions
  4. RSA SecurID Interview Questions
  5. Archer GRC Interview Questions
  6. RSA Archer Interview Questions
  7. Blockchain Interview Questions
  8. Commvault Interview Questions
  9. Peoplesoft Admin Interview Questions
  10. ZooKeeper Interview Questions
  11. Apache Kafka Interview Questions
  12. Couchbase Interview Questions
  13. IBM Bluemix Interview Questions
  14. Cloud Foundry Interview Questions
  15. Maven Interview Questions
  16. VirtualBox Interview Questions
  17. Laravel Interview Questions
  18. Logstash Interview Questions
  19. Elasticsearch Interview Questions
  20. Kibana Interview Questions
  21. JBehave Interview Questions
  22. Openshift Interview Questions
  23. Kubernetes Interview Questions
  24. Nagios Interview Questions
  25. Jenkins Interview Questions
  26. Chef Interview Questions
  27. Puppet Interview Questions
  28. RPA Interview Questions And Answers
  29. Demandware Interview Questions
  30. Visual Studio Interview Questions

Leave a Comment