Python Interview Questions and Answers | Top 125 Python Questions

Python interview questions and answers
Share this:

Top 125 Frequently Asked Python Interview Question and Answers

1. What is Python?
Answer: Python is a high-level, object-oriented scripting language which is interactive and highly readable that will make it ideal for beginner-level programmers. It will use English keywords and has fewer syntactical constructions.

2. What is the difference between list and tuples?
Answer: Following are the difference between list and tuples: List are
1. It is mutable.
2. It is slower.
Syntax: list_1 = [10, ‘Chelsea’, 20].
Tuples are
1. It is immutable.
2. It is faster.
Syntax: tup_1 = (10, ‘Chelsea’ , 20)

3.What is the latest version of Python?
Answer: Latest version of python is Python 3.7.4.

4. What is pickling and unpickling?
Answer: The process of picking will be defined as a module which accepts an object, converts it into a string, and will dump into a file using dump function. Unpickling is the process of retrieving Python objects from the stored string.

5.How are Arguments Passes by Reference or By Value? 
Answer: Everything in Python is like an object. All variables will hold different references to the objects. The values of references will be as per their functions. The programmer will not change the value of the references. However, he will change the objects if they are mutable.

6. How can you access a session in Flask?
Answer: A session will allow the programmer for remembering information from one request to another. In a flask, a session
will use a signed cookie therefore the user will look at the contents and modify. The programmer can be able to modify the session only if it has the secret key Flask.secret_key.

7. What is lambda? Why do lambda forms not have statements?
Answer: Lambda is an anonymous expression function which is often used as an inline function. Its form will not have a statement as it can be only used for making new functional objects and then will return them at the runtime.

8. What is the module and package in Python?
Answer: The module is a way for structuring a program. Each Python program will be a module, which will import other modules like objects and attributes. The entire folder of the Python program is a package of modules. A package will have both modules or sub folders.

9. What are the rules for global and local variables in Python?
Answer: Local variables are a new value to a variable anywhere within the function's body. The variables which are referenced inside a function are called as global.

10. How is it possible to share global variables across various modules?
Answer: You require to create a special module, to share global variables across different modules within a single program. Import the config module in all of the modules of the application. This can make the module available as a global variable across all the modules.

11.What is a negative index in Python?
Answer:Indexing Python sequences in both positive and negative numbers will be possible. For the positive index, 0 will be the first index, 1 will be the second index and so on. For the negative index, (-1) will be the last index and (-2) will be the second last index and so on.

12. What is pass in Python? What are the differences between pass and continue?
Answer: Pass means there is a no-operation Python statement. It will be just a placeholder in a compound statement where nothing can be written. The continue will make the loop to resume from the next iteration.

13. Explain what is a Flask? What are its benefits?
Answer: A Flask is called as a micro web framework for Python based on the "Werkzeug, Jinja 2. Flask is part of the micro-framework, it will have little or no dependencies on the external libraries. A Flask will make the framework light while taking little dependency and provides fewer security bugs.

14. Name the arithmetic operators supported by Python.
Answer: Python will not support the unary operators; rather, it will support augmented assignment operators.
The arithmetic operators, following are supports-
Addition- '+'
Subtraction- '-'
Multiplication- '*'
Division- '/:
Modulo division- '%'
Power of- '**'
Floor div- '//'

15. What is PEP 8?
Answer:PEP 8 is the coding convention to make the Python coding more relatable. It is a set of recommendations which are used for making the codes executable and modular.

16. What is MRO in python?
Answer:Method resolution order or MRO will refer to when one class inherits from multiple classes. The class which is inherited, is called the parent class and the class which inherits, is called the child class. It will also refer to the order where the base class is searched while executing the method.

17. What is the use of repr function in Python?
Answer:This function will return to a printable presentation for the provided object. It will take a single object and its syntax is repr(obj). The function repr will compute all the formal string representation for the given object in Python.

18. Narrate the difference between Python arrays and lists.
Answer: Both lists and arrays in Python will store the data in the same way. The difference is- Array List
It will hold single data type elements. It in Python can hold any type of data element.

19. What is Python magic method?
Answer:It will refer to the method which can add a certain value to the class. It will not be initiated by the user rather only it will occur when an internal action will take charge. In python, the built-in classes can define a number of magic methods.

20. What is the difference between repr and str in Python?
Answer: Repr() Str()

  1. It is unambiguous It is readable
  2. It will be implemented for any class
  3. Implement in case of the string version
  4. Used for computing official Used for computing informally
  5. It displays object Displays string representations

21. What is typecasting in python?
Answer: The entity which can change the data types from one form to another is known as typecasting. In programming languages, it can be used for making sure the variables will be processed in the correct sequence by the function.
Example for while converting an integer to string.

22. What are the advantages of using Python?
Answer: Following are the advantage of using Python:
1. Extensive Support Libraries
2. Extensive Integration Features
3. Improves Programmer's Productivity
4. Platform Independent

23. What is the type () in Python?
Answer: The built-in method which will decide the types of the variable at the program runtime is called as type() in Python. When a single argument will be passed through it, then it will return given object type. When three arguments can pass through this, then it will return a new object type.

24. Who is the creator of Python?
Answer: Guido van Rossum

25. What do you mean by interpreted programming language?
It is an interpreted programming language in which the code will get directly executed without compilation.

26. Tell some benefits of Python.
Benefits of Python
1. It is Dynamic language
2. It can support object-oriented programming languages
3. It will not have a concept of access modifiers like private,
public, and protected but you will use magic functions for using
the methods as public or private.
4. It will a very simple syntax that can make it easy to learn.
5. Apart from desktop application python can also be used for
web development.

27. What is a Dynamic type Language?
Unlike other programming languages in Python for every variable, we will not need for declaring its data type. That will makes Python a Dynamic language. Example for var1=10 # var1 is an integer type var2 =“Hello world” #

28. Name the tool in python which is used to find Bugs.
Answer: var2 is a string PyChecker and Pylint.

29. What pass keyword do and why do you use it?
Answer: The pass is a special keyword in the python that will perform the NULL operation when you will execute a pass keyword nothing will happen. In python, if you will declare if statement or a function you will have to define the function and the statement if you will not define them the python interpreter through an error. To overcome this error, you will use the pass keyword inside the if statements and functions. example for
remove_h=”hello world”

for i in remove_h:
if i==h:
pass
else:
print(i)
Output
h
e
l
l
o
w
o
r
l
d

30. Write code to get the current file directory.
Answer: import os
print(os.__file__)
#output
Users\user_name\AppData\Local\Programs\Python\Python37- 32\lib\os.py

31. Name all the inbuild datatype in python:
Answer: Python has following inbuilt data types
1. Numbers
2. Strings
3. List
4. Tuples
5. Dictionaries
6. Sets

32. What are Mutable and Immutable Datatypes.
Answer: 1. Mutable are those data types in python whose value will be changed. Example for list, Dictionaries, and Sets
2. Immutable are those data types once they will be assigned you will not able to manipulate their values. Example for Strings, Tuples and Numbers.

33. Comment on Python Memory management.
Answer: Python interpreter will handle memory management. It will use private heaps to control and maintain a memory. In python the user will not get any access related to its memory management, python memory management will take control of all the memory action by itself. Python will have an automatic garbage collector.

34. Write a code to convert 144 into a string.
Answer: str(144)

35. What is a lambda function?
Answer: Lambda function is an anonymous function which will be written in a single line. example for # Normal function in python
def mul(a,b):
return a*b

mul(10,20)
#lambda function
mul=lambda a,b : a*b
mul(10,20)

36. What are the methods of a class?
Answer: Methods are the functions, that can be defined inside a class. example for class Animal:
def method_1(self):
pass
def method_2(self):
print(“hello world”)

37. What is a __init__ method?
Answer:__init__ method is a reserved method of a class is also called as
the constructor of a class. Whenever you will initialize an
instance of a class the __init__ method automatically calls.
Example for
class Animal:
def __init__(self):
print(“I am an Animal”)
def method_1(self):
pass
dog=Animal() #instance of a class
Output
I am an Animal

38. What are the Exceptions in Python?
Answer:Exceptions are the errors which will occur during the execution of code.

39. What Raises an Exception?
Answer:In python, we will raise an Error by using a statement raise and all the statements after it cannot execute.
example for
print(“hello”)
raise ValueError
print(“world”)
Output
hello
ValueError

40. Does Python have a concept of inbuilt Array?
Answer: Python will have a list but they are not Arrays. Python will not have support for in-built array data type but you will use the array with the help of a third-party library Numpy.

41. What range function does in python?
Answer: Range() is a special function often use in python, it can be used for iterating over a number of the sequence. range function will accept three arguments initial state, last state and the steps will be taken to reach the last point.
example for
for i in range(2,10,2)
print(i)
Output
2
4

6
8

42. What are dictionaries in python and how they are different from a list?
Answer: A dictionary is an in-built data type in python that will consist of a pair of key and values separated by a colon(:).
Dictionary syntax:
dic= {“key1”: “value1”, “key2”:”value2”}
Dictionaries are the unorder collections of keys and values whereas a list is an ordered collection of values.
In the list, we will use the index for calling a value but in dictionaries, we will use keys to call the corresponding value.

43. What error will be shown if you index a key that is not a part of the dictionary?
Answer: KeyError

44. What is slicing in python?
Answer: Slicing will provide more control for the user over a string or a list. With the help of slicing, you will retrieve any sequence of values that you want.
example for
# List slicing
lis=[1, ”hello”,3, ”world”,5,6,7, ”I am”,”here”]
print(lis[2:6])
print(list[3:8:2])
Outputs
[3,”world”,5,6]
[“world”,6,”I am”]

45. How memory is managed in Python?
Answer: Memory is managed in python in following way:

1. Memory in Python Can be managed by Python private heap space. All Python objects and data structures will be located in a private heap. The programmer can not have an access to the private heap and this private heap in Python will be taken care by Python Interpreter.

2. Python memory manager will be responsible in allocating Python heap space for Python objects.

3. Python has an inbuilt garbage collector, that will recycle all the unused memory and frees the memory and will make it available to the heap space.

46. What are the tools that help to find bugs or perform static analysis?
Answer:

PyChecker: PyChecker is a static analysis tool which will find bugs in the Python source code and will raise alerts about the issues in the style or code complexity.

Pylint: Pylint will check if a module meets the coding standards.

47. What are Python decorators?
Answer: Python decorators will allow programmers to add functionality to an existing code. It will to wrap a function in order for extending the behavior of wrapped function, without permanently modifying it.

48. What are the different environment variables identified by Python?
Answer: Environment variables, that will be recognized by Python are
1. PYTHONPATH
2. PYTHONSTARTUP
3. PYTHONCASEOK
4. PYTHONHOME

49. What is PYTHONPATH?
Answer: PYTHONPATH is an environmental variable which is identified by Python that will tell the interpreter where to locate the module files imported into a program.

50. What is PYTHONSTARTUP?
Answer: PYTHONSTARTUP is an environmental variable which is identified by Python that contains the path of an initialization file containing Python source code.

51. What is PYTHONCASEOK?
Answer: PYTHONCASEOK is an environmental variable which is identified by Python that will be used in windows to instruct
Python for finding the first case-insensitive match in an import statement.

52. What is PYTHONHOME?
Answer: PYTHONHOME is an environmental variable which is identified by Python that is an alternative module search path. Usually it will be embedded in the PYTHONSTARTUP or PYTHONPATH directories for making switching module libraries easy.

53. What is a Name in Python?
Answer: A Name in Python is also called as Identifier. It is a way for accessing a variable. It is simply a name provided to the objects. We can declare a variable by just assigning a name to it in python.

54. What is the Namespace in Python?
Answer: A Namespace is a naming system that is used for ensuring the names are unique for each and every object which is might be a variable or a method in Python for avoiding naming conflicts. Based on the namespace, Python interpreter can understand what exact method or variable one is trying for pointing to in the code.

55. What is a scope in Python?
Answer: We will not be able to access all of the namespaces from every part of the program. Scope will refer to the coding region from where a namespace will be accessed.

56. What are iterators in Python?
Answer: In Python, iterators can be used for iterating containers such as a list or a group of elements. Iterator implements __itr__ and next() method for iterating the stored elements. In Python, we will use loops to iterate over the collections (list, tuple).

57. What is slicing in Python?
Answer: Slicing is a string operation used for selecting a range of items from sequence type such as list, tuple, and string. The slice object will represent the indices specified by range(start, stop, step). The slice() method can allow three parameters that is start, stop, and step.

1. start – starting number for the slicing to begin.
2. stop – the number which indicates the end of slicing.
3. step – the value to increment after each index (default = 1).

Although we will get elements by specifying an index. In Python, a string (say text) will begins at index ‘0’, and the nth character stores at ‘n-1’. We will also do reverse indexing using negative numbers. By doing this we will get only single element whereas using slicing we will get a group of elements. It can be beneficial and easy to get elements from a range by using slice.

58. What is a dictionary in Python?
Answer: Dictionary in python is a collection that is unordered, changeable and indexed. Dictionaries will be written with curly
brackets, and the elements in python dictionaries which are stored as key-value. Dictionaries can be indexed by keys and can be optimized for retrieving values when the key is known.
The keys are unique whereas values be be duplicate.

59. What is Pass in Python?
Answer: Pass statement is a null operation. Nothing will happen when it will execute. Pass statement can help to pass the control without an error when we require to create an empty class or function.
Example:
If(x>100)
print(“Python Interview Questions”)
else
pass

60. What statement is used in Python if the statement is required syntactically but there is no execution of code or command?
Answer: We will use Pass statement.

61. What is the command to debug a Python program?
Answer: The command used for running a Python program in debug mode is $ python -m pdb python-script-file-name.py

62. What are parameters and arguments in python?
Answer: A parameter is a variable which can be passed during the declaration of a function.
An argument is the actual value of the variable parameter that will get passed to the function. When a function will be called, the arguments can be the actual value we pass into the function’s parameters.
// x and y are parameters
// function definition
def add(x,y):
return x+y
// 10 and 20 are arguments
// function call
result=add(10,20)
print(result)

63. Are arguments pass by value or pass by reference in Python?
Answer: Python neither will passe by value nor by reference. Python will passe by ‘Assignment‘. Everything in python is an object. The parameter we pass is originally a reference for the object not the reference to a fixed memory location. We will not change the value of the references but we will change the objects if it is mutable.

64. What’s the Difference between a List and a Dictionary?
Answer: Following are the differences between List vs Dictionary:

List:
1. A Python List will be used for storing a sequence of elements which are mutable. Therefore the elements will be modified after they can be created. They will be of any data type. They are the same or they are mixed.
2. Elements in lists can always accessed through numeric, zero- based indices.
3. Lists will be used whenever you will have a collection of items in an order

Dictionary:
1. A Python dictionary will be an unordered collection of key- value pairs. Dictionaries can be indexed by keys and can be optimized for retrieving values when the key is known. The keys are unique whereas values may be duplicate.
3. Elements in the dictionary will be accessed by using their key.
4. A dictionary will be used whenever you will have a set of unique keys that map to values.

65. How would you get a list of all the Keys in a Dictionary?
Answer: To get a list of all the keys in a dictionary, You can use function keys():
mydict={‘x’:90,’y’:91,’z’:92}
mydict.keys()
dict_keys([‘x’, ‘y’, ‘z’])

66. When Would You Use a List vs. a Tuple vs. a Set in Python?
Answer: A Python List will be used for storing a sequence of elements which are mutable. Therefore the elements will be modified after they can be created. They will be of any data type. They are the same or they are mixed. It is ideal for projects which can demand the storage of objects that may be changed later.

Tuples Can be immutable. An immutable objects will not be modified. We will not able to modify a tuple object after it is created. Tuples operation has smaller size than list, which will make it a bit faster. It is ideal for projects which will demand a list of constants.

A Python Set will be used for storing a collection of unique elements. It can be ideal for projects that demand no duplicate elements in a list. If we will have two lists with common elements between them then we will leverage sets to eliminate them.

67. How to remove duplicate elements from the list in Python?
Answer: There are different ways for removing duplicate elements from the list. One of the methods is for iterating over the list and identify duplicates and remove them. The most popular way for removing duplicate elements from the list is using Sets.
a = [1,4,4,5]
list(set(a))

68. What is lambda in Python?
Answer: A lambda function will be a small anonymous function in Python. It will take any number of arguments, but will only have one expression.
For defining a lambda function, first write keyword lambda instead of def followed by one of more arguments separated by comma, followed by colon sign (:), followed by a single line expression.

Syntax:
lambda arguments : expression

Example:
a = lambda x, y: x * y
a(4, 3) # Call the lambda function
Output: 12

69. What is the difference between Lambda function and normal function (def function) in Python?
Answer: Lambda function Vs. Def function.
• Lambda will contain only one expression and will accept any number of arguments whereas Def will hold multiple
expressions
• Lambda will return a function object which will be assigned to any variable whereas a Def function that contain a
function name, pass the parameter and mandatorily have a return statement
• Lambda will not have return statements whereas Def will have a return statement

70. What is unittest in Python?
Answer: Unittest in Python is a unit testing framework. Unit testing will be the first level of Software Testing. In Unit testing, we can test the smallest testable parts for validating each unit of the software performs as expected.
It will support the following:
• Sharing of setups
• Automation testing
• Aggregation of tests into collections

71. How can you copy an object in Python?
Answer: There are two ways for creating copies in Python
1 Shallow Copy (copy.copy())
2 Deep Copy (copy.deepcopy())

72. What is the difference between deep copy and shallow copy?
Answer: Deep copy:
1. It can not copy the reference to the objects. It means changes are made to a copy of object which is not reflected in
the original object.
2. It will be implemented using “deepcopy()” function.
3. It will make execution of a program slower compared to shallow copy.
Shallow copy:
1. It can copy the reference to the objects. It means changes are made to a copy of object which will reflect in the original object.
2. It will be implemented using “copy()” function.
3. It will make execution of a program faster compared to deep copy.

73. How you can convert an int to a string?
Answer: Python has a built-in function str() to convert an integer number to string. We require to pass an integer number to this function. It can convert the integer to a string.

74. How to convert an integer number to octal string in python?
Answer: Python has a built-in function oct() to convert an integer number to octal. We require to pass an integer number to this function. It can convert the integer to octal string and returns the value.
This function can return a octal string prefixed with ‘0o’

75. How to convert an integer number to hex string in python?
Answer: Python has a built-in function hex() to convert an integer number to hexadecimal string. We require to pass an integer number to this function. It can convert the integer to hexadecimal string and returns the value.
This function can return a lowercase hexadecimal string prefixed with ‘0x’

76. What are control flow statements in Python?
Answer: Usually the flow of execution of a program can run from top- down order in Python. For breaking this top-down order and manipulate the execution flow of a program, we can use control flow statements. These control flow statements can be used whenever a program will take decision depends on the situation like displaying ‘Good morning’ or ‘Good night’ depending on the time. There will be three control flow statements in Python –mi if, for and while.

77. How do we interpret Python?
Answer: Python language is an interpreted language. The program will run directly from the source code and can convert the source code that the programmer can write into an immediate language which is then translated into a language that requires to be executed by a machine.

78. What is a Python decorator?
Answer: A Python decorator is a specific change which is made in Python syntax for effortlessly modifying functions.

79. What are Dict and List Comprehensions?
Answer: These are syntax constructions that help to simplify the creation of a dictionary or list based on iterable that already
exists.

80. What are iterators?
Answer:Iterators can be used for iterating a group of elements, containers such as list.

81. What is slicing?
Answer: Slicing is a mechanism which will help you in selecting a range of items from sequence types like tuple, string, list, etc.

82. What is docstring?
Answer:Docstring is a name of Python documentation string. It is method to document Python modules, classes and functions.

83. What is pass in Python?
Answer:Pass will simply stand for, no-operation Python statement. It will be a place holder in compound statement, where a blank can be left, with nothing written there.

84. Why do lambda forms in Python not have statements?
Answer:A lambda form will not have statements since it can be used in making new function object and returning them at runtime.

86. How do you make a higher order function in Python?
Answer: You have two choices: you will use nested scopes or you will use callable objects. For example, suppose you required to define linear(a,b) which returns a function f(x) which will computes the value a*x+b. Using nested scopes:
def linear(a,b): def result(x):
return a*x + b
return result
Or using a callable object:
class linear:
def __init__(self, a, b):
self.a, self.b = a,b
def __call__(self, x):
return self.a * x + self.b
In both cases:
taxes = linear(0.3,2)
provides a callable object where taxes(10e6) == 0.3 * 10e6 + 2.
The callable object approach has the disadvantage which is a bit slower and results in slightly longer code. However, note that a collection of callables will share their signature via inheritance:

class exponential(linear):
# __init__ inherited
def __call__(self, x):
return self.a * (x ** self.b)
[_private/tbl_gglapck.htm]
Object will encapsulate state for several methods:
class counter:
value = 0
def set(self, x): self.value = x
def up(self): self.value=self.value+1
def down(self): self.value=self.value-1
count = counter()
inc, dec, reset = count.up, count.down, count.set inc(), dec() and reset() act as functions which share the same
counting variable.

86. What is unittest?
Answer:Unittest is an unit testing framework in Python which aids in automation testing, sharing of setups, aggregation of tests into collections, shutdown code tests, etc.

87. What is the difference between Xrange and range?
Answer:While Xrange will return xrange objects, range on the other hand, will return the list and will make use of the same memory irrespective of the range size.

88. How do you delete a file in Python?
Answer:File in python can be deleted by command os.remove (filename) or os.unlink (filename).

89. What is the use of the split function in Python?
Answer: The split function in Python can help in breaking a string into shorter strings by using the defined separator. It will provide a list of the words contained in the string.

90. What are some inbuilt data types in python?
Answer:

Immutable built-in datatypes of Python
1. Numbers
2. Strings
3. Tuples

Mutable built-in datatypes of Python
1. List
2. Dictionaries
3. Sets

91. What is inheritance in python?
Answer: Inheritance will derive the properties of one class to or can inherit it from some another class. Python can support the following types of inheritance.
1. Single Inheritance – where a derived class can acquire the members of a single superclass.
2. Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 will be inherited from base2.
3. Hierarchical inheritance – from one base class you will inherit any number of child classes
4. Multiple inheritance – a derived class can be inherited from more than one base class.

92. Write some of the common errors.
Answer: Following are some common errors:
1. TypeError: It will Occur when the expected type doesn’t match with the given type of a variable.
2. ValueError: It will Occur When an expected value is not given. If you are expecting 4 elements in a list and you gave 2.
3. NameError: It will Occur When trying to access a variable or a function that is not defined.
4. IOError: It will Occur When trying to access a file that does not exist.
5. IndexError: It will be accessing an invalid index of a sequence can throw an IndexError.
6. KeyError: When an invalid key can be used for accessing a value in the dictionary.

93. How to import a module/library?
Example:We can import any library or module in the code using the import keyword. import sklearn is a machine learning library.

94. What is the difference between deep and shallow copy?
Answer: Deep copying will not change the original function that is copied. While deep copying can makes copies of original function into a new one. Shallow copying can save the reference of the original one. Deep copying can copy the structure only. Shallow copying can copy the function and structure. We will make changes to one function for shallow and they will get reflected in another. This can not be done in the deep copy.

95. Get the missing number from an integer list 1-100.
Answer: Following is yntax to get missing number from an integer list.
def get_missing_number(l):
nxt = 1
while nxt < len(l):
if nxt != l[nxt-1]:
return nxt
nxt = nxt + 1

There are many other ways for solve above problem and more concise ones. For example, you create a set of numbers from 1 to 100 and can remove all elements in the list l. This is an elegant solution as it can return not one but all numbers that are missing in the sequence. Here is this solution:
set(range(l[len(l)-1])[1:]) – set(l)

Following is an alternative solution:
lst = list(range(1, 101))
lst.remove(55)
total = sum(range(max(lst) + 1))
print(total – sum(lst))

96. Find duplicate number in integer list.
Answer: Assume we have a list of integer numbers which is called elements. The goal is for creating a function which will find ALL integer elements in that list which are duplicated, that is that will exist at least two times in the list.

For example, when applying our function to the list elements=[2, 2, 3, 4, 3], it can return a new list [2, 3] as integer elements 2 and 3 will be duplicated in the list elements.

Lets start coding. Here is my first attempt:
def find_duplicates(elements):
duplicates = set()
seen = set()
for element in elements:
if element in seen: # O(1) operation duplicates.add(element)
seen.add(element)
return list(duplicates)
l = [2, 2, 2, 3, 4, 3, 6, 4, 3]
print(find_duplicates(l))
# [2, 3, 4]

Note that the runtime complexity will be pretty good. We will iterate over all elements once in the main loop. The body of the main loop has constant runtime because a set for both variables “duplicates” and “seen” have been selected. Checking whether an element is in a set, and adding an element to the set has constant runtime (O(1)). Therefore , the total runtime complexity is linear in the input size.

97. Check if a list contains an integer x.
Answer: To check whether a Python list can contain an element x in Python, will be done by iterating over the whole list and checking whether the element can be equal to the current iteration element. In fact, this can be my choice as well, if the list elements are complex objects which are not hashable.

As integer values are hashable, Simply use the Python “in” keyword as mentioned.
l = [3, 3, 4, 5, 2, 111, 5]
print(111 in l)
# True

98. Find the largest and the smallest number in an unsorted list.
Answer: Following is a simple solution for Python:
l = [4, 3, 6, 3, 4, 888, 1, -11, 22, 3]
print(max(l))
# 888
print(min(l))
# -11

Following is an alternative solution :
def find_max(l):
maxi = l[0]
for element in l:
if element > maxi:
maxi = element
return maxi
l = [4, 3, 6, 3, 4, 888, 1, -11, 22, 3]
print(max(l))
# 888

99. Find pairs of integers in a list so that their sum is equal to the integer x.
Answer: This problem is interesting. The simple solution is to use two nested ‘for loops’ and check for each combination of elements whether their sum is equal to integer x. Here is what I mean:
def find_pairs(l, x):
pairs = []
for (I, element_1) in enumerate(l):
for (j, element_2) in enumerate(l[i+1:]):
if element_1 + element_2 == x:
pairs.add((element_1, element_2))
return pairs
l = [4, 3, 6, 3, 4, 888, 1, -11, 22, 3]

print(find_pairs(l, 9))

Fail! It will show an exception: “AttributeError: ‘list’ object has no attribute ‘add’”
This is what I meant: it’s easy to underestimate the difficulty level of the puzzles, only to learn that you did a careless mistake again. So the corrected solution is this:

def find_pairs(l, x):
pairs = []
for (I, element_1) in enumerate(l):
for (j, element_2) in enumerate(l[i+1:]):
if element_1 + element_2 == x:
pairs.append((element_1, element_2))
return pairs
l = [4, 3, 6, 3, 4, 888, 1, -11, 22, 3]

print(find_pairs(l, 9))

Now it depends whether your interviewer will accept this answer. The reason is that you have a lot of duplicated pairs. If it is asked to remove them, you may simply do a post- processing by removing all the duplicates from the list.

# Solution from user Martin
l = [4, 3, 6, 4, 888, 1, -11, 22, 3]
match = 9
res = set([(x, match – x) for e, x in enumerate(l) if x <=

match / 2 and match – x in l[:e] + l[e+1:]]) print(res)

lst = [(10,5), (10,5), (5,10), (3,2), (3, 4)]
lst = list(set(lst))
print(lst)
# [(3, 4), (10, 5), (5, 10), (3, 2)]

100. Remove all duplicates from an integer list.
Answer:The goal is for removing all elements, that will exist more than once in the list. Note that you will be careful not to remove elements while iterating over a list.

Wrong example of modifying a list while iterating over it
lst = list(range(11))
for element in lst:
if element>=6
lst.remove(element)
print(lst)

Modifying the sequence over which you will iterate causes unspecified behavior. After it can remove the element 5 from the list, the iterator can increase the index to 6. The iterator will assume this is the next element in the list. However, that is not the case. As we have removed the element 5, element 6 is now at position 5. The iterator simply will ignore the element.

Hence, you will get this unexpected semantics. There is a much better way how for removing duplicates in
Python. You have to know which sets in Python allow only a single instance of an element. There after converting the list to a set, all duplicates can be removed by Python. I approach will be checking all pairs of elements whether they are duplicates, this method has linear runtime complexity. The reason is to create of a set is linear in the number of set elements. Now, we will simply have to convert the set back to a list and the duplicates should be removed.

lst = list(range(9)) + list(range(9))
lst = list(set(lst))
print(lst)
# [ 0, 1, 2, 3, 4, 5, 6, 7, 8,]

101. Sort a list with the Quicksort algorithm.
Answer: The main idea of Quicksort is for selecting a pivot element and then placing all elements which are larger or equal than the pivot element to the right and all elements which are smaller than the pivot element to the left. Now, you will have divided the big problem of sorting the list into two smaller subproblems: sorting the right and the left partition of the list. This list is already sorted, Therefore the recursion can terminates. Following is the quicksort algorithm as a Python one-liner:

def qsort(L):
if L == []: return []
return qsort([x for x in L[1:] if x< L[0]]) + L[0:1] +
qsort([x for x in L[1:] if x>=L[0]])
lst = [44, 33, 22, 5, 66, 55, 999]
print(qsort(lst))
# [5, 22, 33, 44, 55, 66, 999]

102. Sort a list with the Mergesort algorithm.
Answer: Mergesort algorithm has the idea is to break up the list into two sublists. For each of the sublist, you can call merge sort in a recursive manner. Assuming that both lists will be sorted, you will merge the two sorted lists. Note that it can be very efficient to merge two sorted lists: it will take only linear time in the size
of the list.

Following is the algorithm solving this problem.
def msort(lst):
if len(lst)<=1: return lst
left = msort(lst[:len(lst)//2])
right = msort(lst[len(lst)//2:])
return merge(left, right)
def merge(lst1, lst2):
if len(lst1)==0: return lst2
if len(lst2)==0: return lst1
merged_list = []
index_lst1 = 0
index_lst2 = 0
while len(merged_list) < (len(lst1) + len(lst2)):
if lst1[index_lst1] < lst2[index_lst2]:
merged_list.append(lst1[index_lst1])
index_lst1 += 1
if index_lst1 == len(lst1):
merged_list += lst2[index_lst2:]
else:
merged_list.append(lst2[index_lst2])
index_lst2 += 1
if index_lst2 == len(lst2):
merged_list += lst1[index_lst1:]
return merged_list
lst = [44, 33, 22, 5, 77, 55, 999]
print(msort(lst))
# [5, 22, 33, 44, 55, 77, 999]

103. Check if two strings are anagrams.
Answer: Two words are anagrams, if they are consist of exactly the same characters. It will define it a bit more precisely: “Ananagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once”.

Here are a few examples:
“listen” → “silence”
“funeral” → “real fun”
“elvis” → “lives”

Okay, you Should know exactly what is right to do?

def is_anagram(s1, s2):
return sorted(s1) == sorted(s2)
s1 = “elvis”

s2 = “lives”
s3 = “not”
s4 = “hello”

print(is_anagram(s1, s2)) # True

print(is_anagram(s2, s3)) # False
print(is_anagram(s2, s4)) # False
print(is_anagram(s2, s1)) # True

The program can solve the problem efficiently and correctly. But this is not my first attempt. I will be suffered the old
weakness of programmers: starting to code to early. I can use a hands-on approach and created a recursive function
is_anagram(s1, s2). I used the observation that s1 and s2 are anagrams iff (1) they willhave two equal characters and (2) they can still anagrams if we will remove these two characters the smaller problem) While this solution worked out, it will also suck out 10 minutes of my time. Two strings are anagrams if they will have the same sorted character sequence. It’s that easy.

104. Compute the intersection of two lists.
This problem are seem to be easy. If you have some library knowledge such as numpy, you will solve this problem with a single function call. For example, Python’s library for linear algebra like numpy has an implementation of the intersection function. Still we can assume that we will NOT have any library knowledge in the coding.The intersection function will take two lists as input and returns a new list which will contain all elements that can exist in both lists.

Following is an example of what we required to do:
1. intersect([1, 2, 3], [2, 3]) → [2, 3]
2. intersect([“hi”, “my”, “name”, “is”, “slim”, “shady”], [“i”,
“like”, “slim”]) → [“slim”]
• intersect([3, 3, 3], [3, 3]) → [3, 3]

You will use the following code to do this.
def intersect2(lst1, lst2):
res = []
lst2_copy = lst2[:]
for el in lst1:
if el in lst2_copy:
res.append(el)
lst2_copy.remove(el)
return res

# Are the results ok?
print(intersect([1, 2, 3], [2, 3]))
# [2, 3]
print(intersect(“hi my name is slim shady”.split(“ “),
“I like slim”.split(“ “)))
# [‘slim’]
print(intersect([3, 3, 3], [3, 3]))
# [3, 3]
# Are the original lists untouched?
lst1 = [4, 4, 3]
lst2 = [3, 4, 2]
print(intersect(lst1, lst2))
# [4, 3]
print(lst1)# [4, 4, 3]
print(lst2)
# [3, 4, 2]

Therefore, we got the semantics right that will be enough to pass the interview. The code will correct and it can ensure that the original list is not touched. I cannot think so! My first idea to use sets again on that we will
perform operations like set intersection. But when using sets, we will lose the information about duplicated entries in the list. Therefore a simple solution in this direction will not be in sight.

Then, I be thinking about list comprehension . The first idea is to use list comprehension like following: def intersect(lst1, lst2): lst2_copy = lst2[:]
return [x for x in lst1 if lst2.remove(x)]

However, do you have the problem with this approach?

The problem is that intersect([4, 4, 3], [4, 2]) returns [4, 4]. This is a clear mistake! It is not easy for seeing – I have found many online resources that simply ignore this problem.

The number 4 will exist twice in the first list but if you can check “4 in [4, 2]”, it returns True – no matter how often you are checking. That’s why we requires to remove the integer number 4 from the second list after finding it the first time.

105. Reverse string using recursion.
Answer: Following are coding for reversing a string using recursion.

Following we want to achieve:
1. “hello” → “olleh”
2. “no” → “on”
3. “yes we can” → “nac ew sey”
There is a restriction on the solution: you will have to use recursion. Roughly speaking, the function will call itself on a smaller problem instance. Clearly, the following strategy will solve the problem in a recursive way. First, you can take the first element of a string and move it to the end. Second, you can take the rest of the string and recursively repeat this procedure until only a single character is left.

Following is the code:

def reverse(string):
if len(string)<=1:
return string

else:
return reverse(string[1:]) + string[0]

phrase1 = "hello"
phrase2 = "no"
phrase3 = "yes we can"
print(reverse(phrase1))
# olleh
print(reverse(phrase2))
# on
print(reverse(phrase3))
# nac ew sey

The program will move the first element to the end and calling the function recursively on the remaining string.

106. Find all permutations of a string.
Answer: A permutation will from a string by reordering its characters. Two anagrams will be permutations from each other as construct the one from the other by reordering characters.
Following are all permutations from a few example strings:
• ‘hello’ → {‘olhel’, ‘olhle’, ‘hoell’, ‘ellho’, ‘lhoel’, ‘ollhe’, ‘hlleo’,
‘lhloe’, ‘hello’, ‘lhelo’, ‘hlelo’, ‘eohll’, ‘oellh’, ‘hlole’, ‘lhole’,
‘lehlo’, ‘ohlel’, ‘oehll’, ‘lleoh’, ‘olleh’, ‘lloeh’, ‘elhol’, ‘leolh’,
‘ehllo’, ‘lohle’, ‘eolhl’, ‘llheo’, ‘elhlo’, ‘ohlle’, ‘lohel’, ‘elohl’,
‘helol’, ‘loehl’, ‘lheol’, ‘holle’, ‘elloh’, ‘llhoe’, ‘eollh’, ‘olehl’,
‘lhleo’, ‘loleh’, ‘ohell’, ‘leohl’, ‘lelho’, ‘olelh’, ‘heoll’, ‘ehlol’,
‘loelh’, ‘llohe’, ‘lehol’, ‘holel’, ‘hleol’, ‘leloh’, ‘elolh’, ‘oelhl’,
‘hloel’, ‘lleho’, ‘eholl’, ‘hlloe’, ‘lolhe’}
• ‘hi’ → {‘hi’, ‘ih’}
• ‘bye’ → {‘bye’, ‘ybe’, ‘bey’, ‘yeb’, ‘eby’, ‘eyb’}

Conceptually, you can assume about a string as a bucket of characters. Assume the string has length n. In following case, you will have n positions for filling from the bucket of n characters. Having filled all n positions, you can obtain a permutation from the string. You will want to find ALL like permutations. solving this problem recursively. Assume, we already know all permutations from a string with n characters. We will want to find all permutations with n+1 characters by summing a character x. We can obtain all such permutations by inserting x into each position of an existing permutation.

We can repeat this for all existing permutations. There is the Johnson-Trotter algorithm but this is difficult solution to present at a coding interview.
def get_permutations(word):
# single word permutations
if len(word)<=1:
return set(word)
# solve smaller problem recursively
smaller_perms = get_permutations(word[1:])
# find all permutation by inserting the first character # to each position of each smaller permutation
perms = set()
for small_perm in smaller_perms:
for pos in range(0,len(small_perm)+1):
perm = small_perm[:pos] + word[0] +
small_perm[pos:]
perms.add(perm)
return perms
print(get_permutations(“nan”))
print(get_permutations(“hello”))
print(get_permutations(“coffee”))
# {‘nna’, ‘ann’, ‘nan’}
# {‘olhel’, ‘olhle’, ‘hoell’, ‘ellho’, ‘lhoel’, ‘ollhe’, ‘hlleo’,
‘lhloe’, ‘hello’, ‘lhelo’, ‘hlelo’, ‘eohll’, ‘oellh’, ‘hlole’, ‘lhole’,
‘lehlo’, ‘ohlel’, ‘oehll’, ‘lleoh’, ‘olleh’, ‘lloeh’, ‘elhol’, ‘leolh’,
‘ehllo’, ‘lohle’, ‘eolhl’, ‘llheo’, ‘elhlo’, ‘ohlle’, ‘lohel’, ‘elohl’,
‘helol’, ‘loehl’, ‘lheol’, ‘holle’, ‘elloh’, ‘llhoe’, ‘eollh’, ‘olehl’,
‘lhleo’, ‘loleh’, ‘ohell’, ‘leohl’, ‘lelho’, ‘olelh’, ‘heoll’, ‘ehlol’,
‘loelh’, ‘llohe’, ‘lehol’, ‘holel’, ‘hleol’, ‘leloh’, ‘elolh’, ‘oelhl’,
‘hloel’, ‘lleho’, ‘eholl’, ‘hlloe’, ‘lolhe’}
# {‘coeeff’, ‘ceoeff’, ‘ceofef’, ‘foecef’, ‘feecof’, ‘effeoc’,
‘eofefc’, ‘efcfoe’, ‘fecofe’, ‘eceoff’, ‘ceeffo’, ‘ecfeof’,
‘coefef’, ‘effoce’, ‘fceefo’, ‘feofce’, ‘fecefo’, ‘ocefef’,
‘ffecoe’, ‘ofcefe’, ‘fefceo’, ‘ffeoce’, ‘ffoeec’, ‘oefcfe’,
‘ofceef’, ‘efeofc’, ‘eefcof’, ‘ceffoe’, ‘eocfef’, ‘ceffeo’,
‘eoffec’, ‘ceoffe’, ‘fcoefe’, ‘cefofe’, ‘oeeffc’, ‘oeffec’,
‘fceeof’, ‘ecfofe’, ‘feefoc’, ‘ffcoee’, ‘feocef’, ‘ffceeo’,
‘fofcee’, ‘fecfoe’, ‘fefoec’, ‘eefcfo’, ‘eofcfe’, ‘ffceoe’,
‘ofcfee’, ‘ceefof’, ‘effoec’, ‘offcee’, ‘fofeec’, ‘eecffo’,
‘cofefe’, ‘feeofc’, ‘ecofef’, ‘effceo’, ‘cfeefo’, ‘ffeoec’,
‘eofcef’, ‘cffeeo’, ‘cffoee’, ‘efcefo’, ‘efoefc’, ‘eofecf’,
‘ffeceo’, ‘ofefec’, ‘foeecf’, ‘oefefc’, ‘oecffe’, ‘foecfe’,
‘eeffoc’, ‘ofecfe’, ‘oceeff’, ‘offece’, ‘efofce’, ‘fcoeef’,
‘fcofee’, ‘oefecf’, ‘fcefeo’, ‘cfefoe’, ‘cefoef’, ‘eoceff’,
‘ffoece’, ‘feofec’, ‘offeec’, ‘oceffe’, ‘eeoffc’, ‘cfoeef’,
‘fefcoe’, ‘ecoeff’, ‘oeecff’, ‘efofec’, ‘eeffco’, ‘eeofcf’,
‘ecfefo’, ‘feoefc’, ‘ecefof’, ‘feceof’, ‘oeefcf’, ‘ecffoe’,
‘efecfo’, ‘cefeof’, ‘fceofe’, ‘effeco’, ‘ecfoef’, ‘efeocf’,
‘ceeoff’, ‘foceef’, ‘focfee’, ‘eoeffc’, ‘efoecf’, ‘oefcef’,
‘oeffce’, ‘ffocee’, ‘efceof’, ‘fcfeeo’, ‘eoefcf’, ‘ocffee’,
‘oeceff’, ‘fcfeoe’, ‘fefeoc’, ‘efefco’, ‘cefefo’, ‘fecfeo’,
‘ffeeco’, ‘ofefce’, ‘cfofee’, ‘cfefeo’, ‘efcoef’, ‘ofeecf’,
‘eecoff’, ‘ffeeoc’, ‘eefofc’, ‘ecoffe’, ‘coeffe’, ‘eoecff’,
‘fceoef’, ‘foefec’, ‘cfeeof’, ‘cfoefe’, ‘efefoc’, ‘eeocff’,
‘eecfof’, ‘ofeefc’, ‘effcoe’, ‘efocef’, ‘eceffo’, ‘fefeco’,
‘cffeoe’, ‘feecfo’, ‘ecffeo’, ‘coffee’, ‘feefco’, ‘eefocf’,
‘fefoce’, ‘fofece’, ‘fcefoe’, ‘ocfeef’, ‘eoffce’, ‘efcofe’,
‘foefce’, ‘fecoef’, ‘cfeoef’, ‘focefe’, ‘ocfefe’, ‘eocffe’,
‘efocfe’, ‘feoecf’, ‘efecof’, ‘cofeef’, ‘fcfoee’, ‘oecfef’,
‘feeocf’, ‘ofecef’, ‘cfeofe’, ‘feocfe’, ‘efcfeo’, ‘foeefc’}

107: Check if a string is a palindrome.
Answer: A palindrome is a word, number, phrase, or other sequence of characters that will reads the same backward as forward, like madam or racecar or the number 10201.

Following is a palindrome example
1. “Mr. Owl ate my metal worm”
2. “Was it a car or a cat I saw?”
3. “Go hang a salami, I’m a lasagna hog”
4. “Rats live on no evil star”
5. “Hannah”
6. “Anna”
7. “Bob”
This is like there is a short and concise one-liner solution in Python.
def is_palindrome(phrase):
return phrase == phrase[::-1]
print(is_palindrome(“anna”))
print(is_palindrome(“kdljfasjf”))
print(is_palindrome(“rats live on no evil star”))
# True
# False
# True

108. Compute the first n Fibonacci numbers.
Answer:The series are appearing in unexpected areas like economics, mathematics, art, and nature. The series can start with the Fibonacci numbers zero and one. Then, you will calculate the next element of the series as the sum of both last elements. The algorithm has to keep track only of the last two elements in the series. Therefore we can maintain two variables a and b, being the second last and last element in the series, respectively.

# Fibonacci series:
a, b = 0, 1
n = 10 # how many numbers we calculate
for i in range(n):
print(b)
a, b = b, a+b
##1
##1
##2
##3
##5
##8
##13
##21
##34
##55

I used the language feature of multiple assignments in the first and the last line for clarity of the code.
This feature will work as follows. On the left-hand side of the assignment, there will be any sequence of variables like a list or a tuple. On the right-hand side of the assignment, you can specify the values to be assigned to these variables. Both sequences on the left and on the right will must have the same length. Otherwise, the Python interpreter can throw an error.
Note that all expressions on the right-hand side will first be evaluated before they can be assigned otherwise the last line can be wrong as expression ‘a+b’ will consider the wrong value for ‘a’.

109. Use a list as stack, array, and queue.
Answer: Start to use a list in three different ways: as a stack, as an array, and as a queue.

# as a list …
l = []
l.append(3) # l = [3]
l.append(4) # l = [3, 4]
l += [7, 8] # l = [3, 4, 7, 8]
l.pop(0) # l = [4, 7, 8]
# … as a stack …
l.append(11) # l = [4, 5, 6, 11]
l.append(12) # l = [4, 5, 6, 10, 12]
l.pop() # l = [4, 5, 6, 11]
l.pop() # l = [4, 5, 6]
# … and as a queue
l.insert(0, 5) # l = [5, 4, 5, 6]
l.insert(0, 3) # l = [3, 5, 4, 5, 6]
l.pop() # l = [3, 5, 4, 5]
l.pop() # l = [3, 5, 4]
print(l)
# [3, 5, 4]

110. Search a sorted list in O(log n).
Answer: The most popular algorithm which will solve this problem is the binary search algorithm. Following are some of the applications:

Applications of the binary search algorithm will include sets, trees, dictionaries, bags, bag trees, bag dictionaries, hash sets, hash tables, maps and arrays. The sorted list is consist of eight values. Suppose, you require to find the value 56 in the list.

The trivial algorithm will go over the whole list from the first to the last element comparing each against the searched value. If your list will contain n elements, the trivial algorithm can result in n comparisons. Therefore, the runtime complexity of the trivial algorithm is O(n).

The goal is to traverse the sorted list in logarithmic time O(logn). So we will not afford to touch each element in the list. The binary search algorithm in the graphic repeatedly will probe the element in the middle of the list rounding down.

There are three following cases:
1.This element x is larger than the searched value 55. In this case, the algorithm will ignore the right part of the list as all elements which are larger than 55 as well. This is because the list can be already sorted.
2. The element x is smaller than the searched value 55. This is the case, we can observe in the figure. Following the algorithm which can ignore the left part of the list as they can be smaller as well again, using the property that the list is already sorted.
3. The element x is equal to the searched value 55. You will see this case in the last line in the figure. Now you already have found the element in the list!
In each phase of the algorithm, the search space can be reduced by half! This means that after a logarithmic number of steps, we have found the element.
After having understood the algorithm, it will be easy to come up with the code. Here is my version of the binary search algorithm.

def binary_search(lst, value):
lo, hi = 0, len(lst)-1
while lo <= hi:
mid = (lo + hi) // 2
if lst[mid] < value:
lo = mid + 1
elif value < lst[mid]:
hi = mid – 1
else:
return mid
return -1

l = [3, 6, 14, 16, 33, 55, 56, 89]
x = 56
print(binary_search(l,x))
# 6 (the index of the found element)

111. Why can't I use an assignment in an expression?
Answer: Many people used to C or Perl complain which they can want to
use this C idiom:
while (line = readline(f)) {
…do something with line…
}
where in Python you will be forced to write this:
while True:
line = f.readline()
if not line:
break
The reason to not allow assignment in Python expressions is a common, there is hard-to-find bug in those other languages, caused by this construct:
if (x = 0) {
…error handling…
}
else {
…code that only works for nonzero x…
}

The error is a simple typo: x = 0, which can assign 0 to the variable x, was written while the comparison x == 0 is certainly what will be intended. Many alternatives will be proposed. Most are hacks which can save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it will be intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct. An interesting phenomenon is the most experienced Python programmers recognize the "while True" idiom and will not seem to be missing the assignment in expression construct much.

There are an alternative way of spelling this which will seem attractive but is generally less robust than the "while True" solution:
line = f.readline()
while line:
…do something with line…
line = f.readline()
[_private/tble_firefox.htm]

The problem with this is that if you will change your mind about exactly how you will be getting the next line example for you want to change it into sys.stdin.readline()) you can have to remember to change two places in your program — the second occurrence can be hidden at the bottom of the loop.
The best approach can be to use iterators, making it possible for looping through objects using the for statement. For
example, in the current version of Python file objects will be support the iterator protocol, therefore you can write simply:
for line in f:
… do something with line…

112. Is there a tool to help find bugs or perform static analysis?
Answer: Yes. PyChecker is a static analysis tool which will find bugs in Python source code and will warn regarding code complexity and style. Pylint is also a tool which can check if a module is satisfying a coding standard, and also can make it possible for writing plug-ins to add a custom feature.

113. How do you set a global variable in a function?
Answer: x = 1 # make a global
def f():
print x # try to print the global

for j in range(100):
if q>3:
x=4
Any variable which is assigned in a function can be local to that
function. Unless it will be specifically declared global. Therefore
a value will be bound to x as the last statement of the function
body, the compiler can assume that x is local. Consequently the
print x can attempt to print an uninitialized local variable and
can trigger a NameError.
The solution is for inserting an explicit global declaration at the
start of the function:
def f():
global x

print x # try to print the global

for j in range(100):
if q>3:
x=4
In this case, all references to x will be interpreted as references to the x from the module namespace.

114. What are the rules for local and global variables in Python?
Answer: In Python, variables which are only referenced inside a function will be implicitly global. If a variable will assign a new value anywhere within the function's body, it can be assumed to be a local. If a variable will have a new value inside the function, the variable can implicitly local, and you will be required to explicitly declare it as 'global'.

Though a bit surprising at first, a moment's consideration can explains this. Requiring global for assigning variables will provide a bar against unintended side-effects. If global will be required for all global references, you'd be using global all the time. You will have to declare as global every reference for a builtin function or to a component of an imported module. This clutter will defeat the usefulness of the global declaration for
identifying side-effects.

115. How do I share global variables across modules?
Answer: The canonical way for sharing information across modules within a single program is for creating a special module often called config or cfg. Import the config module in all modules of your application; the module then will become available as a global name. Because there will be only one instance of each module, any changes made to the module object will be reflected everywhere.

For example: config.py: x = 0 # Default value is configuration setting
mod.py: import config
config.x = 1
main.py:
import config
import mod
print config.x

116. How can I pass optional or keyword parameters from one function to another?
Answer: Collect the arguments using the * and ** specifier in the parameter of function list; this will provide you the positional arguments as a tuple and the keyword arguments as a dictionary. You will then pass these arguments when calling another function by using * and **:
def f(x, *tup, **kwargs):

kwargs['width']='14.3c'

g(x, *tup, **kwargs)

In the unlikely case that you will be care about Python versions older than 2.0, use 'apply':
def f(x, *tup, **kwargs):

kwargs['width']='14.3c'

apply(g, (x,)+tup, kwargs)

117. Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?
Answer: Start with Python 2.2, you can use S.rstrip("\r\n") for removing all occurences of any line terminator from the end of the string S without removing other trailing whitespace. If the string S will represent more than one line, with several empty lines at the end, the line terminators for all the blank lines can be be removed:
>>> lines = ("line 1 \r\n"
… "\r\n"
… "\r\n")
>>> lines.rstrip("\n\r")
"line 1 "
Since this will typically only desired when reading text one line at a time, using S.rstrip() this way will work well.

118. How do I copy an object in Python?
Answer: Usually we keep by copy.copy() or copy.deepcopy() for the general case. Some objects are copied more easily. Dictionaries have a different copy() method:
newdict = olddict.copy()
Sequences are copied by slicing:
new_l = l[:]

119. How can I find the methods or attributes of an object?
Answer: For an instance x of a user-defined class, dir(x) which return an alphabetized list of the names that contains the instance attribute and methods and attributes defined by its class.

120. How do I convert a string to a number?
Answer: For integers, use the built-in int() type constructor, example for int('144') == 144. Means float() will convert to floating-point, example for float('144') == 144.0. By default, these will interpret the number as decimal, therefore that int('0144') == 144 and int('0x144') will raise ValueError. int(string, base) can take the base for converting from as a second optional argument, therefore int('0x144', 16) == 324. If the base will be specified as 0, the number is interpreted by Python's rules: a leading '0' will indicate octal, and '0x' indicates a hex number.

Do not use the built-in function eval() if all you require is to convert strings to numbers. eval() can be significantly slower and it will present a security risk:
someone can pass you a Python expression which might will have unwanted side effects. For example, someone will pass __import__('os').system("rm -rf $HOME") which can erase your home directory.
eval() will also has the effect of interpreting numbers as Python expressions, therefore example for eval('09') provides a syntax error because Python regards numbers starting with '0' as octal (base 8).

121. How can my code discover the name of an object?
Answer: It will not, because objects will not really have names. Assignment always will bind a name to a value; The same is true of def and class statements. in these case the value is a callable. The following is code :
class A:
pass
B = A
a = B()
b = a
print b
<__main__.A instance at 016D07CC>

print a
<__main__.A instance at 016D07CC>
The class has a name: even though it will bound to two names and invoked through the name B the created instance will be still reported as an instance of class A. However, it will be impossible fir saying whether the instance's name is a or b, since both names will be bound to the same value.

Generally speaking it is not necessary for code to know the names of particular values. Unless you will be writing introspective programs, this can usually an indication which will a change of approach might be beneficial. In comp.lang.python, Fredrik Lundh once provided an excellent analogy in answer to this question:
The same way as you will get the name of that cat you will found on your porch: the cat (object) itself will not tell you its name, and it will not really care — therefore the only way for finding out what it is called is for asking all your
neighbours namespaces if it's their cat (object)…

122. Is there an equivalent of C's "?:" ternary operator?
Answer: No.

123. How do I convert a number to a string?
Answer: For converting , example for the number 144 to the string '144', you can use the built-in function str(). If you required a hexadecimal or octal representation, you can use the built-in functions hex() or oct(). For nice formatting, use the % operator on strings, example for "%04d" % 144 will yield '0144' and "%.3f" % (1/3.0) yields '0.333'.

124. How do I modify a string in place?
Answer: You will not because strings are immutable. If you require an object with this ability, try To convert the string to a list or use the array module:
>>> s = "Hello, world"
>>> a = list(s)
>>>print a
['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']>>> a[7:] = list("there!")
>>>''.join(a)
'Hello, there!'
>>> import array
>>> a = array.array('c', s)
>>> print a
array('c', 'Hello, world')
>>> a[0] = 'y' ; print a
array('c', 'yello world')
>>> a.tostring()
'yello, world'

125. How do I use strings to call functions/methods?
Answer: There are many techniques to use call functions or methods
1. The best is for using a dictionary that it will map strings to functions. The primary advantage of this technique is that the strings will not require to match the names of the functions. This is also called the primary technique used for emulating a case construct:
def a():
pass
def b():
pass
dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
dispatch[get_input()]() # Note trailing parens to call function
*
Use the built-in function getattr(): import foo
getattr(foo, 'bar')()
Note that getattr() will work on any object,which include classes, class instances, modules.

This will be used at several places in the standard library, such as: class Foo:
def do_foo(self):

def do_bar(self):

f = getattr(foo_instance, 'do_' + opname)
f()
Use locals() or eval() to resolve the function name:
def myFunc():
print "hello"
fname = "myFunc"
f = locals()[fname]
f()
f = eval(fname)
f()
Note: Using eval() is slow and dangerous. If you will not have absolute control over the contents of the string, someone can pass a string which will be resulted in an arbitrary function being executed.

 

Python is the most popular general purpose high level program language now in days. Python is now highly preferable language for developing integrated and robust web applications.

Also, due to its simple syntax, high readability and easy to adapt features making most of programmers fall in love with Python. Due to its simplicity, it became one of the most favorable programming languages for Artificial Intelligence, Data science and Machine learning applications.

As we expect AI, Machine learning, Data Science and Web applications are here to stay for several more years, the demand for Python is only going to increase. For the past few years, Python has been the most in-demand programming language and we expect it ti continue for few more years.

The above 125 Top Python interview questions were compiled to help Python programmers community. Please go through these frequently asked Python interview questions to get better prepared for your next job interview.

Share this:

Leave a Comment

Your email address will not be published. Required fields are marked *