Python Interview Questions

1) What is Python? Discuss some uses?
Python is popular programming language created in 1991.
> Python can be used on a server to create web applications.
> Python can be used alongside software to create workflows.
> Python can connect to database systems. It can also read and modify files.
> Python is nowadays widely used in Machine Learning, Deep Learning, Artificial intelligence, and more
> Python can be used to handle big data and perform complex mathematics.
> Python can be used for rapid prototyping or production-ready software development.
> In the near future, Python will be able for making Android Apps too
2) What is PEP 8?
PEP 8 is a coding convention, a set of recommendations, about how to write your Python code more readable.
3) What is the difference between python 2 and python 3? (Company: Expedia)
Python 2
> Stable and Transparent
> Print statement is treated as statement and not function.
> ASCII string type is used by default to store strings
> Range function reconstructs the sequence every time
> It returns an integer to the nearest whole number when dividing two integers

Python 3
> It is the future of python
> The print syntax is treated as a function
> Unicode is the implicit string type by default
> The range is replaced by range() function
> It makes integer division more intuitive by using true division for integers and floats

4) What is the identifier?
A Python identifier is a name used to identify a variable or function or class or module or another object.
5) What are the rules to write identifiers?
An identifier should start with letter A -Z or a-z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).
6) What are Reserved Words?
Keywords in python are Reserved Words. You cannot use them as constant or variable or any other identifier names. All keywords in python contain lowercase letters only.
7) What are the comments? What it's use?
Comments are a way to improve the readability of code by explaining what we have done in the code in simple English. By reading the comment one can understand the purpose of the code much faster than by just going through actual code.
8) What happens when # characters are encountered inside the quotes?
When # character is encountered inside quotes, it is not considered as comment.
9) What are command-line arguments?
> They are passed to the main() function.
> They are parameters/arguments supplied to the program when the program is invoked.
> They are used to control the program from outside instead of hard coding those values inside code.
10) What is sys.argv? Can you use it?
sys.argv is a list of command-line arguments passed to the Python program. argv represents all the items that come along from command line input, it is an array holding command-line arguments of our program. Counting starts at zero (0), not one (1).
To use sys.argv, you will have to import sys. The first argument, sys.argv[0], is the name of the program as it was invoked, and sys.argv[1] is the first argument you pass to the program.

import sys
program_name=sys.argv[0]
arguments=sys.argv[1:]
count=len(arguments)

11) What are the data types in python?
Following are the data types in python
> Integer
> Float
> Complex
> String
> List
> Tuple
> Dictionary
12) How to remove an item from the list?
There are many methods to remove an item from a list: The remove() method removes the item that is specified. The pop() method removes index specified, The del keyword removes the specified index. The del keyword can also delete list completely. The clear() method can empty the list
13) What is the difference between iterator and iterable?
Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers from where you can get an iterator. All these objects have a iter() method which is used to get an iterator
mytuple = (“a”, “b”, “c”)
myiterator = iter(mytuple)
print(next(myiterator))
print(next(myiterator))
print(next(myiterator))
14) How to create an iterator? (Company: TripAdvisor)
To create an iterator you have to implement the methods __iter()__ and __next()__. The __iter()__ method acts similarly, you can do operations (initializing, etc.), but must always return iterator object itself. The next() method also allows us to do operations and must return the next item in the sequence.
15) What is the difference between generator function and normal function?
The basic difference between generator function and normal function is:
> The generator function has a yield statement.
> When called, it returns an object that is an iterator but does not start execution immediately.
> Methods like iter() and next() are implemented automatically. So iteration through items using next() is possible.
> Finally, when the function ends, the StopIteration method is raised automatically on further calls.
16) What is lambda? Can you use it in your program?
A lambda function is a small anonymous function. A lambda function is a function that can take any number of arguments, but the limitation is that it can only have one expression. Syntax of lambda is –
lambda arguments: expression
Example: x = lambda g: g **2
print(x(9))
17) Can you loop thought a dictionary?
One can loop through a dictionary using a for a loop. When looping through a dictionary, the return value is the keys of the dictionary, but there are methods to return the values as well.
for x in mydict:
    print(x)
18) How to write a basic package?
Packages are nothing but namespaces that have other packages and modules. Each package in Python is a directory that should necessarily contain a file called __init__.py. This file can be empty, and it indicates that the directory it contains is a Python package, so it can be imported in the same way a module can be imported.
19) What are object methods?
Objects can also contain methods. Methods in objects are functions that belong to the object. Let us create a method in the Person class:
class Person:
    def _ _init__(self, name, age):
        self.name = name
        self.age = age
    def myfunc(self):
        print(“Hello my name is ” + self.name)
        p1 = Person(“Selmon Bhai”, 90) p1.myfunc()
20) What is inheritance?
Inheritance allows us to define a class in such a way that inherits all the methods and properties of another class. The parent class is the class being inherited from, and it is also called a base class. The child class is the class that inherits from another class, and it is also called the derived class.
21) What is super function? (Company: Tumbtack)
super() function is a function that will make the child class inherit all the methods and properties from it’s parent
class Student(Person):
    def _ _init__(self, fname, lname):
        super().__init__(fname, lname)
22) What is polymorphism?
The word polymorphism means having many forms. In programming, polymorphism means the function name is the same but different signatures being used for different types
23) Encapsulation VS Data Abstraction?
Data abstraction and encapsulation both are often used as synonyms. Both are nearly the same because data abstraction is achieved through encapsulation.
Encapsulation is an important pillar of object-oriented programming. It is used to restrict access to methods and variables. In encapsulation, code and data are wrapped together within a single unit and protected from being modified by accident.
Abstraction is used to hide internal details and show only functionalities. Abstracting something means to give names to things so that name captures the core of what a function or a whole program does.
24) What is the difference between object-oriented and procedural programming? (Company: Mathworks)
Object-oriented programming is the problem-solving approach and used where computation is done by using objects. It makes development and maintenance easier. It simulates the real-world entity. So real-world problems can be easily solved through oops. It provides data hiding. So it is more secure than procedural languages.

Procedural programming uses a list of instructions to do computation step by step. In procedural programming, It is not easy to maintain the codes when the project becomes lengthy. It doesn’t simulate the real world. It works on step-by-step instructions divided into small parts called functions. Procedural language doesn’t provide any proper way for data binding, so it is fewer data from anywhere. secure.

25) What is a thread?
A thread is an entity inside a process that can be scheduled for execution. It is the smallest unit of processing that can be performed in an OS. A thread is a sequence of instructions within a program that can be executed independently of other codes. It can be assumed that a thread is simply a subset of a process!
26) What information a thread has?
A thread contains all this information in a Thread Control Block (TCB):
> Thread Identifier: Unique id is assigned to every thread
> Stack pointer: Points to thread’s stack in the process.
> Program counter: a register that stores the address of the instruction currently being executed by the thread.
> Thread state: can be running, ready, waiting, start or do.
> Thread’s register set: registers assigned to thread for computations.
> Parent process Pointer: A pointer to the Process control block (PCB) of the process that the thread lives on.
27) What is context switching?
In a simple, single-core CPU, multithreading is achieved by using frequent switching between the threads. This is termed context switching. In context switching, the state of a thread is saved and the state of another thread is loaded whenever an interrupt takes place. Context switching takes place so frequently that all the threads appear to be running parallelly.
28) What is a multithreaded priority queue?
The Queue module allows the user to create a new queue object that can hold a specific number of items. Methods to control the Queue are as follows−
> get() − It removes and returns an item from the queue.
> put() − The put adds the item to a queue.
> qsize() – It returns the number of items that are currently in the queue.
> empty() − It returns True if queue is empty; otherwise, False.
> full() − It returns True if queue is full; otherwise, False.
29) How memory is managed in Python?
> Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap and the interpreter takes care of this Python private heap.
> The allocation of Python heap space for Python objects is done by the Python memory manager. The core API gives access to some tools for the programmer to code.
> Python also has an inbuilt garbage collector, which recycles all the unused memory and frees the memory, and makes it available to the heap space.
30) How Python is interpreted?
Python language is an interpreted language. Python program runs directly from the source code. It converts source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.
31) What are the tools that help to find bugs or perform static analysis?
PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.
32) What is the difference between Xrange and range?
Xrange returns the xrange object while range returns list, and uses same memory and no matter what the range size is.
33) What happens when a function doesn’t have a return statement? Is this valid? (Company: TCS)
Yes, this is valid. The function will then return a None object. The end of a function is defined by the block of code is executed (i.e., the indenting) not by any explicit keyword
34) What is Dogpile effect? (Company: ECIL)
This is defined as an occurrence of event when the cache expires and also when the websites are hit with more number of requests by the client at a time. This dogpile effect can be averted by the use of a semaphore lock. If in the particular system the value expires then, first of all, the particular process receives the lock and begins generating new value.
35) What is the purpose of PYTHONPATH environment variable?
PYTHONPATH – It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.
36) How will you specify source code encoding in a Python source code/file? (Company: TCS, Akuna, Flexport)
By default, every source code file in Python is in UTF-8 encoding. But we can also specify our own encoding for source files. This can be done by adding following line after #! line in the source file.

# -*- coding: encoding -*-

In the above line, we can replace encoding with the encoding that we want to use.

37) What is Pickling in Python?
Pickling is a process by which a Python object hierarchy can be converted into a byte stream. The reverse operation of Pickling is Unpickling. Python has a module named pickle. This module has the implementation of a powerful algorithm for serialization and de-serialization of Python object structure. Some people also call Pickling as Serialization or Marshalling. With Serialization, we can transfer Python objects over the network. It is also used in persisting the state of a Python object. We can write it to a file or a database.
38) What is the difference between a Tuple and List in Python?
In Python, Tuple and List are built-in data structures. Some of the differences between Tuple and List are as follows:

> Syntax: A Tuple is enclosed in parentheses:
E.g. myTuple = (10, 20, “vieh”, “group”);
A List is enclosed in brackets:
E.g. myList = [10, 20, 30];

> Mutable: Tuple is an immutable data structure. Whereas, a List is a mutable data structure.

> Size: A Tuple takes much lesser space than a List in Python.

> Performance: Tuple is faster than a List in Python. So it gives us a good performance.

> Use case: Since Tuple is immutable, we can use it in cases like Dictionary creation. Whereas, a List is preferred in the use case where data can alter.

39) What is the difference between List and Dictionary data types in Python?
Main differences between List and Dictionary data types in Python are as follows:

> Syntax: In a List we store objects in a sequence. In a Dictionary we store objects in key-value pairs.

> Reference: In List we access objects by index number. It starts from 0 index. In a Dictionary we access objects by key specified at the time of Dictionary creation.

> Ordering: In a List objects are stored in an ordered sequence. In a Dictionary objects are not stored in an ordered sequence.

> Hashing: In a Dictionary, keys have to be hashable. In a List, there is no need for hashing.

40) What is a Namespace in Python?
A Namespace in Python is a mapping between a name and an object. It is currently implemented as Python dictionary.
E.g. the set of built-in exception names, the set of built-in names, local names in a function. At different moments in Python, different Namespaces are created. Each Namespace in Python can have a different lifetime. For the list of built-in names, Namespace is created when the Python interpreter starts. When the Python interpreter reads the definition of a module, it creates a global namespace for that module. When a Python interpreter calls a function, it creates a local namespace for that function.
41) What is the use of Pass statement in Python?
The use of Pass statement is to do nothing. It is just a placeholder for a statement that is required for syntax purpose. It does not execute any code or command.
Some of the use cases of pass statement is:
a) It can be used in Syntax Purposes:
Eg:
>>> while True:
………pass # Wait till user input is received
b) It can be used for creating minimal classes:
>>> class VIEHGroup:
……. pass
c) We can also use it as a placeholder for TODO work on a function or code that needs to be implemented at a later point of time.
>>> def initialization():
… pass # TODO
42) What is the use of Generator in Python?
We can use Generator to create Iterators in Python. A Generator is written like a regular function. It can make use yield statement to return data during the function call. In this way we can write complex logic that works as an Iterator. A Generator is more compact than an Iterator due to the fact that _iter_() and next() functions are automatically created in a Generator. Also within a Generator code, local variables and execution state are saved between multiple calls. Therefore, there is no need to add extra variables like self.index etc to keep track of iteration. Generator also increases the readability of the code written in Python. It is a very simple implementation of an Iterator.
43) How will you copy an object in Python?
In Python we have two options to copy an object. It is similar to cloning an object in Java.
1) Shallow Copy: To create a shallow copy we call copy.copy(x). In a shallow copy, Python creates a new compound object based on the original object. And it tries to put references from the original object into copy object.
2) Deep Copy: To create a deep copy, we call copy.deepcopy(x). In a deep copy, Python creates a new object and recursively creates and inserts copies of the objects from original object into copy object. In a deep copy, we may face the issue of recursive loop due to infinite recursion.
44) What is a metaclass in Python? (Company)
A metaclass in Python is also known as class of a class. A class defines the behavior of an instance. A metaclass defines the behavior of a class. One of the most common metaclass in Python is type. We can subclass type to create our own metaclass. We can use metaclass as a class-factory to create different types of classes.
45) What is None in Python?
None is a reserved keyword used in Python for null objects. It is neither a null value nor a null pointer. It is an actual object in Python. But there is only one instance of None in a Python environment. We can use None as a default argument in a function. During comparison we have to use “is” operator instead of “==” for None.
46) What is the use of // operator in Python?
Python provides // operator to perform floor division of a number by another. The result of // operator is a whole number (without decimal part) quotient that we get by dividing left number with right number. It can also be used floordiv(a,b). Eg:
10// 4 = 2
-10//4 = -3
47) What is the difference between append() and extend() functions of a list in Python? (Company)
In Python, we get a built-in sequence called list. We can call standard functions like append() and extend() on a list.
We call append() method to add an item to the end of a list.
We call extend() method to add another list to the end of a list.
In append() we have to add items one by one. But in extend() multiple items from another list can be added at the same time.
48) What is the difference between split() and slicing in Python?
Both split() function and slicing work on a String object. By using split() function, we can get the list of words from a String.
E.g. ‘a b c ‘.split() returns [‘a’, ‘b’, ‘c’]

Slicing is a way of getting substring from a String. It returns another String.
E.g. >>> ‘a b c'[2:3] returns b

49) How do you profile a Python script?
Python provides a profiler called cProfile that can be used for profiling Python code. We can call it from our code as well as from the interpreter. It gives use the number of function calls as well as the total time taken to run the script. We can even write the profile results to a file instead of standard out.
50) How will you share variables across modules in Python?
We can create a common module with variables that we want to share. This common module can be imported in all the modules in which we want to share the variables. In this way, all the shared variables will be in one module and available for sharing with any new module as well.
51) What is the output of following code in Python?
>>>name=’VIEH Group’
>>>print name[:5] + name[5:]

The output of this will be VIEH Group
This is an example of Slicing. Since we are slicing at the same index, the first name[:5] gives the substring name up to the 5th location excluding the 5th location. The name[5:] gives the rest of the substring of the name from the 5th location. So we get the full name as output.
52)What is the difference between .py and .pyc files? (Company)
.py called Python files are Python source files. .pyc files are the compiled bytecode files that is generated by the Python compiler.
53) We know that Python is an object-oriented language, but does it have access specifiers? (Company)
No. Python is a modern object-oriented language that considers the use of access specifiers (like private and public in C++) as primitive and redundant.
54) How to explore a dataset in Python?
There are multiple commands which can help you in exploring a data set. Following are a few commands:
.info()
.describe()
.head()
55) If you have to choose between a list, set, and a dictionary to store 10 million integers, what will you use? Bear in mind that you would later like to query the frequency of a number within the dataset.
Since we have to cater for multiple occurrences of a number, we can’t choose a set, since it doesn’t store duplicates by design. To find the frequency of a number within a list, you will have to iterate it completely, resulting in an O(n) complexity for searching, which is inefficient. A dictionary, however, lets you store key-value pairs. You can store a number as the key and the number of times it has been stored, as the value. This way, whenever you want to query the frequency, you can get the result in O(1). This makes a dictionary the best choice in this particular scenario.
56) What do you know about the global interpreter lock?
The Global Interpreter Lock, aka GIL, is a mutex that prevents multiple threads to execute Python bytecode simultaneously. This lock is necessary because the memory management in CPython isn’t thread-safe. This may prevent multi-threaded applications to use multiple CPUs and is, therefore, a bottleneck. However, not all the operations are concerned by the GIL, such as the IO operations or some computation done within libraries (e.g. numpy).
57) What are local variables and global variables in Python?
Global Variables: Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program.
Local Variables:Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.
Example:
a=2 #Global Variable
def add():
    b=3 #Local Variable
    c=a+b
    print(c)
add()

Output: 5
When you try to access the local variable outside the function add(), it will throw an error.

58) What is a negative index, and how is it used in Python?
A negative index is used in Python to index a list, string, or any other container class in reverse order (from the end). Thus, [-1] refers to the last element, [-2] refers to the second-to-last element, and so on.
59) What Does The “Self” Keyword Do?
The self is a Python keyword that represents a variable that holds the instance of an object. In almost all the object-oriented languages, it is passed to the methods as a hidden parameter.
60) Which is the standard data missing marker used in Pandas?
NaN
61) What is pylab?
A package that combines NumPy, SciPy, and Matplotlib into a single namespace.
62) What does _init_.py do?
_init_.py is an empty py file used for importing a module in a directory
63) How can you check whether a pandas data frame is empty or not?
The attribute df.empty is used to check whether a data frame is empty or not.
64) How will you reverse a list in Python?
list.reverse(): This function reverses objects of list.
65) Do we need to declare variables with data types in Python?
No. Python is a dynamically typed language, which means that Python Interpreter automatically identifies the data type of a variable based on the type of value assigned to the variable.
66) Write a command to open the file c: iehgroup.txt for writing.
f= open(“viehgroup.txt”, “wt”)
67) What’s The Process To Get The Home Directory Using ‘~’ In Python?
You need to import the os module, and then just a single line would do the rest. import os print (os.path.expanduser(‘~’)) Output: /home/runner
68) Is There A Switch Or Case Statement In Python? If Not Then What Is The Reason For The Same?
No, Python does not have a Switch statement, but you can write a Switch function and then use it.
69) What Is %S In Python?
Python has support for formatting any value into a string. It may contain quite complex expressions. One of the common usages is to push values into a string with the %s format specifier. The formatting operation in Python has the comparable syntax as the C function printf() has.
70) Explain how Python does Compile-time and Run-time code checking
Most of the python error handling happens at runtime, only few like code syntax validation happen at compile time
71) Is python a case sensitive language?
Yes, Python is indeed a case sensitive language, lets show it with an example, in it we have two variables vieh_group and VIEH_Group . If Python is not case sensitive language then both variables should be same and return same value, right?
vieh_group = “Company 1”
VIEH_Group = “Company 2” print(vieh_group)
print(VIEH_Group)

Output:
Company 1
Company 2

72) How to flush output of Python print?
There are two ways:
Method 1: sys.stdout.flush()

import sys
sys.stdout.flush()
Print by default prints to sys.stdout.

Method 2: flush = True
Since Python 3.3, we have flush parameter, which can be marked as true to by default send flush the output of print command as shown

73) How memory is managed in Python?
Python memory is managed by the Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap. Instead, the interpreter takes care of this Python private heap. The allocation of Python heap space for Python objects is done by the Python memory manager, which can be accessed by the core API. Python also has an inbuilt garbage collector which recycles and frees all the unused memory, making it available to the heap space.
74) What is JSON? How would convert JSON data into Python data?
JSON stands for JavaScript Object Notation. It is a popular data format for storing and transferring data.Generally JSON is built on 2 structures.
> A collection of pairs.
>An ordered list of values.
As Python supports JSON parsers, JSON-based data is actually represented as a dictionary in Python. You can convert JSON data into python using the load() function of the json module.
75) What is multithreading? Give an example.
Threading in python is used to run multiple threads (tasks, function calls) at the same time. Multiple threads within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes. Threads are sometimes called light-weight processes. They do not require much memory overhead and are “cheaper” to run than processes.
76) Which methods of Python are used to determine the type of instance and inheritance?
Python has 2 built-in functions that work with inheritance:
> isinstance(): this method checks the type of instance. Example:
isinstance(myObj, int) – returns True only when “myObj. class ” is “int”.

> issubclass(): this method checks class inheritance Example:
issubclass(bool, int) – returns True because “bool” is a subclass of “int”. issubclass(unicode, str) – returns False because “unicode” is not a subclass of “str”.

77) How do you perform pattern matching in Python? Explain
Regular Expressions/REs/regexes enable us to specify expressions that can match specific “parts” of a given string.
Python’s “re” module provides regular expression patterns and was introduce from later versions of Python 2.5. “re” module is providing methods for search text strings, or replacing text strings along with methods for splitting text strings based on the pattern defined.
78) Explain how to redirect the output of a python script from standout on to a file?
They are two possible ways of redirecting the output from standout to a file.
> Open an output file in “write” mode and the print the contents into that file using the sys.stdout attribute.

import sys
filename = “outputfile” sys.stdout = open() print “testing”

> On the command line, you can redirect the output of a python script to a file. For example:
redirect_output.py has the following code:
print “Testing” execution:python redirect_output.py > outputfile

79) How do you check the file existence and their types in Python?
> os.path.exists(): This method is used to check for the existence of a file. It returns True if the file exists, false otherwise
> os.path.isfile(): This method is used to check whether the give path references a file or not. It returns True if the path references to a file, else it returns false.
> os.path.isdir(): This method is used to check whether the give path references a directory or not. It returns True if the path references to a directory, else it returns false.
>os.path.getsize() Returns the size of the given file os.path.getmtime() Returns the timestamp of the given path.
80) How are the functions help() and dir() different?
These are the two functions that are accessible from the Python Interpreter. These two functions are used for viewing a consolidated dump of built-in functions.

> Help() will display the documentation string. It is used to see the help related to modules, keywords, and attributes, among other things. If no argument is given, the help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

> Dir() is similar to help but will not necessarily return the same results. Without arguments, it will return the list of names in the current local scope. With an argument, it attempts to return a list of valid attributes for that object. When used on an object, dir() attempts to produce the most relevant information for that object. It will not necessarily return a complete listing of information for the object.

How useful was this post?

Click to rate it!

Average rating 4.9 / 5. Vote count: 53

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

Write a comment