Python interview question for Interview | Top 20 Python interview question

Here are my python interview/job preparation questions and answers. Which can help to to clear the interview or also help to take interview of any candidates.

1. What is list ?

List can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.

Lists are a mutable type, i.e. it is possible to change their content.

squares = [1, 4, 9, 16, 25]
nameList = ['p','y','t','h','o','n']

2. What is difference between append, extend and insert ?

append : append object to the end of the list.

append(object)

squares = [1,4,9,16]
squares.append(25) # [1,4,9,16,25]
squares.append([36,49]) # [1,4,9,16,25, [36,49]]

If we append a list in a list then it will not expand the list instead append complete list

insert : inserts an element to the list at the specified index.

insert(index, object)

squares = [1,4,9,16]
squares.insert(1,25) # [1,25,4,9,16]
squares.insert(10,[36,49]) # [1,4,9,16,25, [36,49]]

If we give index position which is out of length then it will insert at end.

extend : Extend list by appending elements from the iterable.

squares = [1,4,9,16]
squares.extend([36,49]) # [1,4,9,16,6,49]
squares.extend(64) # [1,4,9,16,6,49,64]

3. What is the difference between remove, del and pop?

remove : Remove first occurrence of value. Raises ValueError if the value is not present.

remove(value)

squares = [1,4,9,16]
squares.remove(4)
squares # [1,9,16]

pop: Remove and return item at index (default last).

pop(index=-1)

squares = [1,4,9,16]
squares.pop() #16
squares.pop(2) # 9

del : removes an element by index.

squares = [1,4,9,16]
del squares[0]
del #[1,4,9,16]

4. How do we interchange the values ?

a = 10, b = 12
b,a = a,b
print(a,b) #12,10
c = [2,3], d = [1,2]
d,c = c,d
print(c,d) # [1,2], [2,3]

5. What is lambda in Python?

In Python, an anonymous function is a function that is defined without a name.  Anonymous functions are also called lambda functions.

lambda arguments: expression
# Program to show the use of lambda functions
square= lambda x: x * x
print(square(15)) # 225

Also Read: Python – Basic Data Types

6. What is different way copy a list ?

We can copy a list three ways, one is normal way, shallow copy and other is deepcopy.

  • In normal way copy i.e. reference copy we actually copy the reference not only value.
l1 = [1,2,3]
l2 = l1
l1.append(4)
print(l1) #[1,2,3,4]
print(l2) #[1,2,3,4]
  • In shallow copy if list is normal list i.e. not a nested list then shallow copy is useful. There is any change in original list does not affect copied list and vice versa. But if it is nested list then any change in nested list then changes will reflect in both original as well as copied list.
  • For shallow copy you can use one of the following method
    • list(list_name_to_copy)
    • <list_name_to_copy>.copy()
    • <list_name_to_copy>[:]
l1 = [1,2,3]
l2 = list(l1)
l1.append(4)
print(l1) #[1,2,3,4]
print(l2) #[1,2,3]
li3 = [['a'],['b'],['c']]
li4 = list(li3) // OR you can use li3.copy() OR li3[:] (list comprehension)
li3.append([4])
print(li4)#[['a'],['b'],['c']]
print(li3) #[['a'],['b'],['c'], [4]]

#if we change in nested element then li3 and li4 will reflect the changes
li3[0].append('e')
print(li4)#[['a','e'],['b'],['c']]
print(li3) #[['a','e'],['b'],['c'], [4]]
  • In deep copy if we change in nested list of list of original list than it will not change copied list and vice versa
    • for deep copy you need to import copy and use copy.deepcopy()
import copy
li3 = [['a'],['b'],['c']]
li4 = copy.deepcopy(li3)
li3.append([4])
li3[0].append('e)
print(li4)#[['a'],['b'],['c']]
print(li3) #[['a', 'e'],['b'],['c'], [4]]

7. What is the difference between a list and a tuple?

 lists and tuples are data structures in Python. Both are sequential data structure. In both element can be access with the help of index. Both can store homogenous as well as heterogenous data elements.

ListTuple
Lists are mutableTuples are immutable
Methods that add items or remove items are available with list.Methods that add items or remove items are not available with tuple.
We can delete or remove items from a listWe cannot delete or remove items from a tuple.
List elements cannot be used as a key for a dictionary.Tuples that contain immutable elements can be used as a key for a dictionary
Iterations is Time-consumingIterations is less Time-consuming than list
List vs Tuple

Also Read : Python: Operators and Expressions

8. What is the difference between “is” and “==”?

Sometime it feel both work similar way but there is a catch. But both work different way to check equality.

  • Use is to check identity and == to check equality.
  • == compares the values of the objects.
  • is compares the references of the objects.
  • == is for value equality. Use it when you would like to know if two objects have the same value.
  • is is for reference equality. Use it when you would like to know if two references refer to the same object

9. How slice operator work with list

list[start:stop:step]

startOptional. An integer number specifying at which position to start the slicing. Default is 0
endAn integer number specifying at which position to end the slicing
stepOptional. An integer number specifying the step of the slicing. Default is 1

Some use cases of slice operator:

  • Reverse the list
a = [1,2,3,4]
reverse_a = a[::-1] #[4,3,2,1]
name = "singhak"
print(name[::-1])// "kahgnis"
  • Copy the list
a = [1,2,3,4]
b = a[:]
  • Create sub list
a = [1,2,3,4,5,6]
print(a[2:]) #[3, 4, 5, 6]
print(a[2:4]) #[3, 4]
print(a[::2]) #
[1, 3, 5]

print(a[1:5:3]) #[2, 5]

10. What is negative index in Python?

With the help of negative index we can retrieve the element from list. In negative indexing -1 indicate last element of list and similarly -2 indicate second last element and so on.

Negative Indexing in Python
Negative Indexing

11. What’s the difference between raw_input() and input() in python?

In python 3.x raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input()).

In python 3.x input behave same as python 2.x raw_input

name = input('Enter Your name')
#entered value is Singhak
print(type(name)) # <class 'str'>
print(name) #Singhak

In python 2.x input behave different

age= input("Enter the age: ")
# Enter value is 28
print(type(age)) <class 'int'>
print(age) # 28

In Python 3.x, the input function explicitly converts the input you give to type string. But Python 2.x input function takes the value and type of the input you enter as it is without modifying the type.

The raw_input() function is similar to input() function in Python 3.x. Developers are recommended to use raw_input function in Python 2.x.

12. What is the difference between Xrange and range?

In python 2.x range() returns a list and xrange() returns an xrange object, which is kind of like an iterator and generates the numbers on demand.

In python 3.x range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists.

print(list(range(4))) #[0, 1, 2, 3]
print(range(4)) # range(0, 4)

13. What do you mean by list comprehension?

List comprehension is an elegant way to define and create lists based on existing lists. List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.

#Syntax
[expression for item in list]
lst = [x**2 for x in range(5)]
print(lst) # [0, 1, 4, 9, 16]

number_list = [ x for x in range(11) if x % 2 == 0]
print(number_list) # [0, 2, 4, 6, 8, 10]

obj = ["Even" if i%2==0 else "Odd" for i in range(10)]
print(obj) #['Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd']

14. How we can write ternary operator in python?

Ternary operator syntax in python is not same as other language. In python it is different for other.

#Syntax
[on_true] if [expression] else [on_false]

If condition evaluates to True, then on_true is evaluated and returned but on_false is ignored, or else when on_false is evaluated and returned but on_true is ignored.

'true' if True else 'false' #'true'
'true' if False else 'false' #'false'

'Even' if 12%2 == 0 else 'Odd' #'Even'
#it is similar to
if 12%2==0 and 'Even' or 'Odd' # 'Even'

15. How can you remove duplicate element from a list?

We can remove duplicate elements from list using Set or list comprehension and many other ways.

dup_list = [2,4,5,3,2,7,8,4]
non_dup_list = list(set(dup_list))
print(non_dup_list) #[2,4,5,3,7]

#2nd method
non_dup = []
[non_dup.append(x) for x in dup_list if x not in non_dup]
print(non_dup) #[2,4,5,3,7]

16. What is the difference between / and // operator in Python?

"//" operator give the floor value of division.

#//
print(1//2) #0
print(3//2) #1
print(4.0//3) # 1.0
print(4//2) # 2

"/" operator give complete result of division means if result comes with decimal value it will not round off the result.

# /
print(1/2) #0.5
print(3/2) #1.5
print(4.0/3) # 1.3333333333333333
print(4/2) # 2.0

17. How is string interpolation performed?

We can do string interpolation with three ways.

  1. f-strings
  2. %-formatting
  3. Str.format()
  • f-strings
# 1.
name = 'Singhak'
age = 1.3
f"My name is {name} and age is {age}" # 'My name is Singhak and age is 1.3'

#2.
f"{2 * 37}" # "74"

#3.
f"{name.lower()} is Best." # singhak is Best.

#4.
F"Hello, {name}. You are {age}." # "Hello Singhak. You are 1.3"
  • %-formatting
# 1.
name = 'Singhak'
age = 1.3
"Hello, %s. You are %.2f." % (name, age) # 'Hello, Singhak. You are 1.30.'
# 2.
"Hello, %s. You are is %.2f %s." % (name, age, name) # 'Hello, Singhak. You are is 1.30 Singhak.'
  • str.format()
name = 'Singhak'
age = 1.3
person = {'name': 'Singhak', 'age': 14}

#1.
"Hello, {}. You are {}.".format(name, age) # 'Hello, Singhak. You are 1.3.'

# 2.
"Hello, {0}. You are is {1} {0}.".format(name, age, name) # 'Hello, Singhak. You are is 1.30 Singhak.'

# 3.
"Hello, {name}. You are {age}.".format(**person) # 'Hello, Singhak. You are 14.'

#4.
"Hello, {name}. You are {age}.".format(name=person['name'], age=person['age']) # 'Hello, Singhak. You are 14.'

18. How the reduce function works?

reduce takes a function and a sequence and iterates over that sequence. On each iteration, both the current element of sequence and output from the previous element are passed to the function. At the end of itration, a single value is returned.

from functools import reduce
def add(x,y):
    return x + y
lst = [34,56,23,78,90]
reduce(add, lst) # 258

19. How do any() and all() work?

any takes a sequence and returns true if any element in the sequence is true.

If the iterable object is empty, the any() function will return False.

all returns true only if all elements in the sequence are true.

a = [False, False, False]
b = [True, False, False]
c = [True, True, True]
print( any(a) ) # False
print( any(b) ) # True
print( any(c) ) # True

print( all(a) ) # False
print( all(b) ) # False
print( all(c) ) # True

any and all with dictionaries.

# 0 is False
d = {0: 'False'}
print(any(d)) # False

# 1 is True
d = {0: 'False', 1: 'True'}
print(any(d)) # True

########## all

s = {0: 'False', 1: 'False'}
print(all(s)) #False

s = {1: 'True', 2: 'True'}
print(all(s)) # True

s = {1: 'True', False: 0}
print(all(s)) # False

When used on a dictionary, the any() or all() function checks if any of the keys are true, not the values.

20. How is exception handling performed in Python?

Errors that occur at runtime (after passing the syntax test) are called exceptions or logical errors. We can handle these built-in and user-defined exceptions in Python using tryexcept and finally statements. 

#Syntax 1
try:
    # try to do this
except:
    # if try block fails then do this
finally:
    # always do this
#Syntax 2
try:
    # try to do this

finally:
    # always do this
#Syntax 3
try:
    # try to do this
except:
    # if try block fails then do this
else:
    # if the code block inside try ran without any errors

21. How can access the index in ‘for’ loops?

We can use built-in function enumerate(), available in both Python 2 and 3. enumerate() give us both value and index.

#syntax
enumerate(iterable, start=0)
grocery = ['bread', 'milk', 'butter']
enumerateGrocery = enumerate(grocery)

print(type(enumerateGrocery))

# converting to list
print(list(enumerateGrocery))

# changing the default counter
enumerateGrocery = enumerate(grocery, 10)
print(list(enumerateGrocery))

#outputs
<class 'enumerate'>
[(0, 'bread'), (1, 'milk'), (2, 'butter')]
[(10, 'bread'), (11, 'milk'), (12, 'butter')]
grocery = ['bread', 'milk', 'butter']

for item in enumerate(grocery):
  print(item)

print('\n')
for count, item in enumerate(grocery):
  print(count, item)

#outputs
(0, 'bread')
(1, 'milk')
(2, 'butter')

0 bread
1 milk
2 butter

By default index in enumerate() start with 0, we can change it any starting point.

print('\n')
# changing default start value
for count, item in enumerate(grocery, 100):
  print(count, item)

#output
100 bread
101 milk
102 butter

22. How to combine two lists into a list of tuples?

We can use zip() function to combine two or more list and generate list of tuples.

#syntax
zip(*iterables)
number_list = [1, 2, 3]
str_list = ['one', 'two', 'three']

print(list(zip(number_list, str_list)))
# [(2, 'two'), (3, 'three'), (1, 'one')]

Zip two different size of list

str_list = ['one', 'two']
numbers_tuple = ('ONE', 'TWO', 'THREE', 'FOUR')
print(list(zip(str_list, numbers_tuple)))
#[('one', 'ONE'), ('two', 'TWO')]

23. How to check if a value exists in a list or not?

We can use in operator to check any value exist in list or not.

"a" in ["a","b","d","2"]
# True
2 in ["a","b","d","2"]
#False

24. What is the difference between deep and shallow copy?

Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.

Deep copy is used to store the values that are already copied. Deep copy doesn’t copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.

Leave a Reply