Python Interview Questions
Python Interview Questions
Ans:
x = [1, 2, 3]
x.append([4, 5]) 🡪 [1, 2, 3, [4, 5]]
x = [1, 2, 3]
x.extend([4, 5]) 🡪 [1, 2, 3, 4, 5]
� Boolean: the type of build in values True and False. Useful in the conditional expressions and
mostly interchangeable with the integers 1 and 0. False is equalent to 0 and empty sting “”
and all other values equivalent to true
� Numeric types:
o Int, long, float and complex
� Sequences:
o String: string represented as a sequence of 8-bit characters in python 2.x, but as a
sequence of Unicode characters in python 3.x
o Bytes: A sequence of integers in the range of 0-255; only available in python 3.x
o Byte array: like bytes , but mutable .. in python 3.x
o List
o Tuple
� Sets:
o Set: An unordered collection of unique objects
o Frozen set: like set, but immutable
� Mappings:
o dict: Python dictionaries , also called hashmaps or associative arrays.
3. Difference between mutable vs immutable objects
a. Data types in python can be distinguished based on whether objects of the type are
mutable or immutable
b. Immutable types: cannot be changed after they are created.
i. Int, float, long and complex
ii. Str
iii. Bytes
iv. Tuple
v. Frozen set
c. Mutable types: only mutable objects supports methods that change the object in place,
such as reassignment of a sequence slice, which will work for list, but raise an error for
tuple.
i. List,Set and Dict
4. Difference between variable and objects
a. It’s important to understand that variables in python are really just references to objects
in memory.
## below code a,s,l are variable point to the object (values)
a=1
s = ‘abc’
l = [‘a string’, 456, (‘a’, ‘tuple’, ‘inside’, ‘a’, ‘list’)]
� Only mutable objects can be changed in place (l[0] = 1, but s[0] = ‘a’ raise an error)
� For += (increment) operator, when used on an immutable object (a +=1 or in s += ‘qwert’), in
this case python will silently create a new object and make the variable point to it.
However, when used on an mutable object (as in l += [1,2,3]), the object pointed to by the
variable will be changed in place.
p=s
m=l
the s += ‘etc’ and l += [9,8,7] – in this case it will change only s and leave p unaffected, but it
will change both m and l since both point to the same list object. Python builin id() function
…
def append_to_sequence (myseq):
myseq += (9,9,9)
return myseq
tuple2 = append_to_sequence(tuple1)
list2 = append_to_sequence(list1)
This will give the above indicated, and usually unintended, output. myseq is a local variable
of the append_to_sequence function, but when this function gets called, myseq will
nevertheless point to the same object as the variable that we pass in (t or l in our example).
If that object is immutable (like a tuple), there is no problem. The += operator will cause the
creation of a new tuple, and myseq will be set to point to it. However, if we pass in a
reference to a mutable object, that object will be manipulated in place (so myseq and l, in
our case, end up pointing to the same list object).
How to change or delete : it’s not possible directly because string are immutable. Simply we can
reassign the different strings to same name.
🡪String Membership test: ‘a’ in ‘program’ >> True; ‘at’ not in ‘battle’ >> false
🡪builtin function that work with sequence like enumerate(), len(). Enumerate will return an
enumerate object. It contains the index and value of all items.
� ‘helloWorld’.lower()
� ‘helloworld’.upper()
� “This will split all words into a list”.split()
� ‘ ‘.join([‘this’, ‘will’, ‘join’, ‘all’, ‘words’, ‘into’, ‘a’, ‘string’])
� ‘happy new year’.find(‘ew’) >> 7
� ‘Happy New Year’.replace(‘Happy’, ‘Brilliant’)
It consists of brackets containing an expression followed by a for clause, then zero or more for
or if clauses.
Ex: syntax – starts with a ‘[ and ‘]’ the basic syntax is [expression for item in list if conditional]
if conditional:
expression
## one more
Items = [word[0] for word in list_words] >> [‘t’, ‘I’, ‘a’, ‘I’, ‘o’,’w’]
14. How to convert list into dict – l[0] as key and l[1] as values – use zip and dict..
New_dict = {x:y for x,y in zip(list1, list2)}
15. How to convert two list into dict – l1[0] as key and l2[0] as values.
New_dict = {x:y for x,y in zip(list1, list2)}
Ans:
Decorators:
decorators dynamically alter the functionality of a function, method or class without having to
use subclasses.
When you need to extend the functionality of function that you don’t want to modify.
Suppose, you to print the message like ‘test begin’ and ‘test ends’ .. we can do this by using
decoratos
def my_decorator(some_function):
def wrapper():
some_function()
return wrapper
def just_some_function():
print("Wheee!")
just_some_function = my_decorator(just_some_function)
just_some_function()
##OR
@my_decorator
def just_some_function():
print("Wheee!")
just_some_function()
Generators:
Generators simplifies creation of iterators. A generator is a function that produces a sequence of
result instead of single values.
def yrange(n):
i = 0
while i < n:
yield i
i += 1
y = yrange(3)
y.next()
Map: map(func, seq) >> map() can be applied to more than one list with same length.
Filtering: it is a elegant way to filter the options. So it will return only true
Reduce:
a=b
a is b >> true
a = b[:]
a is b >> false
24. What is class method and instance method and static method?
For example:
class Foo(object):
@classmethod
def hello(cls):
print("hello from %s" % cls.__name__)
Foo.hello()
-> "Hello from Foo"
Foo().hello()
-> "Hello from Foo"
Instance Methods
On the other hand, an instance method requires an instance in order to call it, and requires
no decorator. This is by far the most common type of method.
class Foo(object):
def hello(self):
print("hello from %s" % self.__class__.__name__)
Foo.hello()
-> TypeError: hello() missing 1 required positional argument: 'self'
(note: the above is with python3; with python2 you'll get a slightly different error)
Static methods
A static method is similar to a class method, but won't get the class object as an automatic
parameter. It is created by using the @staticmethod decorator.
class Foo(object):
@staticmethod
def hello(cls):
print("hello from %s" % cls.__name__)
Foo.hello()
-> TypeError: hello() missing 1 required positional argument: 'cls'
25. What data types can be used for dictionary keys and what for values.
26. What is oops concept and real time usage?
27. Explain with examples – inheritance, polymorphism, encapsulation and operator over load.
28. Explain with examples – what is class, object, instance and class variable, instance variable.
29. Explain about dynamic memory allocation in python.
30. Regexp to match valid ip address and mac address
31. Regexp to match digits in apple123heloo.
32. What is difference between – re.match, re.search and re.findall methods?
33. How to use re.compile and example?
34. How to open file and remove 5th line and save the data to new file?
35. What are the different possible ways to open files in python?
36. Example of sorting given list of numbers without using any short cut methods?
37. Code to return list of prime numbers? Use map and lambda?
38. Code to get odd and even numbers from given list of numbers?
39. How to access list and dict data with examples?
40. What is rest conf and difference between get, post, put. Simple example in python?
41. Simple telnet code with telnetlib module and explain each step ?
42. Write a simple code to get the top 5 news using selenium?
43. Write code to get total 9 numbers from given list of four numbers?
44. What are the control statements in python and explain about break, continue, pass and pause..
45. What is package
46. How memory management is done in Python
47. How do u modify tuple
48. What is virtual environment in Python.
49. Difference between list.append and list.extend
50. Decorators
51. Match and search
52. Difference between list and tuple in terms of memory and performance
53. What is list.pop do
54. Inheritance
55. What is slicing
56. What are use cases of set
57. try and except
58. Whether dictionary can have same keys for different values and vice versa
59. How lambda is useful
60. pickling and unpickling in python
61. how to read large files in python=f.buffer and f.flush
62. how to introduce sleep in python
63. practical example of tuple ,list
64. how to execute a command on the command line using python program
65. why tuple and list are needed
66. nested dictionaries. what all can be keys
67. os module
68. difference between import and from fn import *
69. where are log and event files stored in windows
70. What is a process
71. Difference between process and threads
72. Import os and from os import *. What is the difference?
73. Real life examples of tuple. Why tuple and list are needed? Why two different things?
74. How does python know to look for user defined modules
75. What are builtin functions and how can we know what they are
76. How to install missing packages
77. What is encapsulation
78. What is method overloading and operator overloading
79. Write a program using add operator overloading to add matrix
80. What is lamba and example with map function
81. What is init method in a class and what is self
82. What is inheritance
83. Where are log files stored in windows and linux
84. how to padd arguments to original function used in a decorator
85. worst code complexity while adding an element to dictionary
86. multi threading
87. why are strings immutable?
88. API calls to execute vm operations like vm power on poweroff load snapshot etc
89. big O notation for code complexity
Programming questions
1. Reverse a sentence
2. To test an anagram
3. Find the second highest number in the list
4. If input is 553, print a fancy number which is like 545 in that series
5. Take a sentence as input and arrange the words and number along with
their count lexicographically
6. Check if password conditions match all criteria of atleast [a-z][A-Z][0-9]
[$#@]
7. Print the count of number between n m which are not divisible by a or
a+d or a+2d or a+3d or a+4d. input is n m a d
8. get the last four elements of the list using slicing when you don’t know
the length of the list
9. find the max sum of contiguous elements in a list with negative
numbers
10. using list comprehension, write all the numbers which are even
between 200-300 and the digits also shld be even
11. how to open and read a log file in python.
12. how to get individual digits from a number
13. how to introduce sleep in python
14. how to execute commands from commandline using python