Python interview questions with answers
This is a growing list hence, the article has been broken down into multiple parts.
January 1, 1 • 1
About The Author
this is meta-description
How to find the occurances of a particular substring in a sentance?
There are many ways of solving the problem.
- Regular Expressions
- Python in-built methods like count()
- Custom Solutions using loops
Regular Expression
100x = "This is a new sentence with many sentences"
101regex=re.compile(r"\bsentence\b")
102regex.findall(x)
The result would be a list of values with the exact match of the word ‘sentence’. Note that, since we use '\bword\b'
, it wont find the word ‘sentences’. If you want ‘sentences’ too then all we have to make a small change to the regular expression
100x = "This is a new sentence with many sentences"
101regex=re.compile(r"sentence")
102regex.findall(x)
Count Method
“This is a new sentence with many sentences”.count(‘sentence’)
This method counts all words and not just whole words
Custom Solutuion We can loop through the words in the sentence and match the exact required word in each item
100l = 0
101for i in s.split():
102 if i == 'sentence':
103 l += 1
104print l
How to join two lists where in if a is [1,2] and b is [3,4], we want the result as a single list of [1,2,3,4] ?
|
|
Given a list of values [1,2], how to get a result list which is like this [1,2,1,2,1,2]
The solution to this problem is very simple.100a = [1,2]
101b = a*3
What is the output of the following code
100s = "COMPUTER"
101print(s[-3:]) #prints TER
102print(s[:-2]) #prints COMPUT
What is the type of the variable a and b
100a = (1)
101print(type(a))
102b = (1,)
103print(type(b))
Hence type(a) is integer and type(b) would be a tuple
Note that the trailing comma is not required if there are more than one item in the tuple.
Given a string ‘COW’ I want the output “COWCOW”, how to do that
100s = "COW"
101print(s*2) #or
102print(s+s)
100a = [1,2,3,4]
101b = a*2
102print(b) # would output [1,2,3,4,1,2,3,4]
Get index of an item while looping a list
We can use the enumerate method to do this100a = [1,2,3,4]
101for index, item in enumerate(y):
102 print(index)
Get the length of a list in python
We can use the len method to do this100a = [1,2,3,4]
101print(len(a)) #outputs 4
we can use the same method on strings to get the number of characters in a string
100a = "abcd"
101print(len(a)) #outputs 4
What does the sorted function print in the following code
100a = sorted('cat')
101b = sorted([3,2,1])
102print(a) #outputs a list ['a','c','t']
103print(b) #outputs a list [1,2,3]
How to sort on the second letter of the word in a list of words in python
We can use the sorted method with an additional parameter
100z = ['kevin','nikolas','Jenny','Craig']
101b = sorted(z, key=lambda k:k[1])
102print(z) #outputs a list ['kevin','Jenny','nikolas','Craig']
Explain count function in python
100x = 'hippo'
101print(x.count('i')) # prints 2
102y = ['cat', 'dog', 'cat']
103y.count('cat') # prints 2
Show the difference between append and extend
100a = [1, 2, 3]
101a.append(4) # a has the value [1,2,3,4]
102a.append([5,6]) # a has the value [1,2,3,4,[5,6]]
103
104b = [1, 2, 3]
105b.extend(4) # throws an error, int object is not iterable
106b.extend([5,6]) # b has the value [1,2,3,4,5,6]
107
108# the above can alse be done using
109b+[5,6]
Explain pop method in python
100x = ['cat', 'dog', 'cat']
101y = x.pop() # y has the last element of the list
We can also pop the list at a particular index
100x = ['cat', 'dog', 'cat']
101y = x.pop(1) # y has the value 'dog'
Explain the output of the following code
100x = []
101y = x.pop()
Throws “IndexError : pop from empty list”
100x = ['cat', 'dog', 'cat']
101y = x.remove('cow')
Throws “ValueError : ‘cow’ not in list”
Explain the difference between sort and sorted method
100x = [6,2,1,8,5]
101x.sort()
102print(x) # x is sorted
103
104y = sorted(x)
105print(x) # x is still unsorted
106print(y)
Sort method does an inplace sort, whereas sorted method takes an argument and returns a sorted list. Original item will still be unsorted.
How are tuples represented
100x = ()
101x = 1,
102x = (1,)
103x = 1,2,3
104x = tuple([1,2,4])
Show some intersting facts about tuples
100x = 1,2,3
101del x[0] # Throws error
102
103x = ([1,2],3)
104del x[0][1] # this deletes the item 2 and x will now be ([1],3)
105
106x = (1,2,3)
107x+=4, # Notice the comma after 4
108print(x) # x is now (1,2,3,4)
We really need to understand what immutable means. Strings are truly immuatable, but tuples seem to have some caveats.
What are sets and how are they represented
A set is a unique list of items without duplicates100# sets are represented like so
101x = {1,2,3}
102y = set()
103
104x.add(4) # now x has {1,2,3,4}
105x.add(4) # adding 4 again has no effect as it is already available in the set
106s.clear() # clears all items
Also, sets can be sorted using sorted function, but not sorted in place
100x = {4,3,2,9,8}
101y = sorted(x) # y is a sorted 'list' [2,3,4,8,9]
102x.sort() # AttributeError: 'set' object has no attribute 'sort'
How are dictionaries represented
There are many ways of representing a dictionary.100x = {'apple':1,'orange':2}
101x = dict([('apple',1), ('orange',2)])
102x = dict(apple=1, orange=2)
Difference between clear and del method
100x = {'apple':1,'orange':2}
101x.clear()
102print(x) # x is now {}
103del x
104print(x) # Throws an error saying 'x' is not defined
While clear()
clears the content of the dictionary, the variable is still intact. The del
method removes the memory location of the variable and hence the variable becomes undefined.
Convert a dictionary into a list of tuples
100x = {1:1, 2:2, 3:3}
101y = x.items() # y will be [(1, 1), (2, 2), (3, 3)]
While clear()
clears the content of the dictionary, the variable is still intact. The del
method removes the memory location of the variable and hence the variable becomes undefined.
Get all positions of an item in a list
100names = ['krishna', 'rama', 'prabhakar', 'krishna', 'prabhakar']
101idx = [k for k,v in enumerate(names) if v == 'krishna']
102print(idx)
103
104# To remove all occurances of an item in a list
105new_name_list = [i for i in in if i != 'prabhakar']
Implement a queue in python
100from collections import deque
101mq = deque()
102mq.append(5)
103mq.append(15)
104print(mq) # prints .. deque([5, 15])
105mq.popleft() # outputs the value 5
Explain the output of the following program
100class Protected:
101 __name = "not accessible"
102 def __method(self):
103 return self.__name
104
105prot = Protected()
106prot.__name # no attribute error
107prot.__method() # no attribute error
Anything that starts with a double __ will be protected by python. Internally the variables that start with __ actually becomes _Protected__variable
.
For example, __name
becomes _Protected__name
This can be known by using the dir(prot)
command, which lists all variables and methods of the class (irrespective of whether they are protected or not)
Please have a look at the other parts of the same article
Related Posts
Python interview questions with answers part 2
This is a growing list hence, the article has been broken down into multiple parts [1. Python Interview questions part 1](.
Read moreJavascript interview questions with answers
What are the advantages of using JSON rather than using xml JSON is a lightweight format for storing and transferring data.
Read moreHow to maintain multiple versions of django without using using virtual envs.
Most linux come installed with python 2.7. Some even come installed with both 2.7 and 3 as well. django upto version 1.
Read more