# Python Interview Questions Programming

Here are the top Python interview questions and answers that cover a wide base of topics associated with Python such as the use of the assert statement, the difference between Shallow copy vs deep copy, decorators in Python. Go through these Python interview question-answer sets and land your dream job as a Python Developer, Full Stack engineer, and other top profiles. Practice these interview questions on Python with answers provided by experts and be fully prepared for your next Python interview.

• 4.5 Rating
• 28 Question(s)

## Beginner

Python code does not need to be compiled as is an interpreted language. In python, we don’t have to declare the data type of the variable while assigning a value to it as is dynamically typed. It allows us to use object oriented programming concepts. In python anything and everything is considered as an object, therefore a class is an object and a function is also an object. We can run python codes very quickly.

Global Interpreter Lock (GIL) is a construct in python. GIL ensures that only one of the threads is executed at any given time. The limitation is that we will be using the same cpu core for every thread and using the multi-threading library will not allow us to use all the other cpu cores while executing the threads.

O/p:
[0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0, 1, 4]
Explanation:
lst_mem = []
lst = lst_mem           # Here is the first call
for i in range(2):
lst.append(i*i)
print(lst)            # [0, 1]
lst = [3,2,1]         # Here is the second call
for i in range(3):
lst.append(i*i)
print(lst)            # [3, 2, 1, 0, 1, 4]
lst = lst_mem           # Here is the third call
for i in range(3):
lst.append(
i*i)
print(lst)

O/p:

[0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0, 1, 4]

Yield is a keyword used to convert a function into a generator. It is similar to a return keyword. Yield returns the generator object.

Example for yield keyword using generators:

def testgen(index):
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
yield weekdays[index]
yield weekdays[index+1]
yield weekdays[index+2]
yield weekdays[index+3]
yield weekdays[index+4]
yield weekdays[index+5]
yield weekdays[index+6]
day = testgen(0)
print (next(day), next(day), next(day), next(day), next(day), next(day), next(day))

O/p:

sun mon tue wed thu fri sat

Index Error: List Index out of range

Using the ' '.join() method. This will join all the elements of a list into a long string. We have to pass the list of elements to the join method as an argument.

For example:

weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsString = ' '.join(weekdays)
listAsString
Output(o/p):
'sun mon tue wed thu fri sat'
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsString = ' '.join(weekdays)
print(listAsString)

O/p:

sun mon tue wed thu fri sat

We can use the tuple function to convert a list into a tuple. Since list is mutable, and tuple is immutable, once a list gets converted to a tuple, it becomes immutable. That means that after converting list to a tuple, we cannot modify the elements in it.

weekdays = ['sun','mon','tue','wed','thu','fri','sat']

listAsTuple = tuple(weekdays)

print(listAsTuple)

By using the set function as follows:

weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsSet = set(weekdays)
print(listAsSet)

O/p:

{'sun', 'thu', 'mon', 'tue', 'wed', 'sat', 'fri'}

numbers = (1, 2, 3, 4)

result = map(lambda x: x*x, numbers)
print(result)
# converting map object to set
print(numbersSquare)

O/p:

<map object at 0x000001CA835AFCC0>

{16, 1, 4, 9}

Explanation:

numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)
result
print(result)

O/p:

<map object at 0x000001CA835D4400>

# converting map object to set
print(numbersSquare)

O/p:

{16, 1, 4, 9}

# converting map object to a list
print(numbersSquare)

O/p:

[1, 4, 9, 16]

s is a dictionary with the key as 13 and value as a list of elements ‘foo’ and ‘bar’

So the output of s is as follows:

{13: ['foo', 'bar']}

The output of t is an empty list so the output of t is:

[]

Let’s find out the data type of variable curr or object curr as anything and everything in python is an object including class and a function too.

so when we type(curr) the output is:

NoneType

The out of variable i is equal to an integer with value equal to 1 as assigned

Since s is a dictionary with only one key and its value the value of n is 1

As the len(s) is equal to 1. As the length of the dictionary s is equal to 1.

By using the count() function.

For example:

weekdays_list = ['sun','mon','tue','wed','thu','fri','sun','mon','mon']
print(weekdays_list.count('mon'))

O/p:

3

def div1(x,y):
print "%s/%s = %s" % (x, y, x/y)
def div2(x,y):
print "%s//%s = %s" % (x, y, x//y)
div1(5,2)
div1(5.,2)
div2(5,2)
div2(5.,2.)

The o/p of the code in python2 is as follows:

5/2 = 2

5.0/2 = 2.5

5//2 = 2

5.0//2.0 = 2.0

In python2.x by default, when a division operation is performed, it performs integer arithmetic if both the operands are arithmetic in nature.

Therefore in python 2.x,  5/2 will result in 2 whereas 5.0/2 will result in 2.5

This behaviour can be overridden using from__future__import division

Also // operator will always result in integer division regardless of the datatypes of the operands. Therefore 5.0//2.0 will result in 2.0 in python 2.x

However, in python3.x, it will not result in integer arithmetic if both the operands are integers so in python3.x the o/p will be as follows:

5/2 = 2.5

5.0/2 = 2.5

5//2 = 2

5.0//2.0 = 2.0

The output will be an empty list i.e. the o/p will be [] and it will not result in an IndexError.

Here we are not attempting to access the member of a list whereas we are trying to access a slice of a list at a starting index which is greater than the length of the list itself, however, it will not result in an IndexError and it will simply return an empty list.

The o/p is n

This uses the concept of list slicing where the index of a list from the rightmost corner will start from -1.

n=int(input('Enter number of elements?'))         #Step1
list1=[]                                      #Step2
for i in range(n):                            #Step3
element=int(input('Enter number:'))           #Step4
list1.append(element)                     #Step5
#print(list1)
average=sum(list1)/n                          #Step6
print('Average of given numbers is:',average) #Step7

'''
'''

Step1: Enter number of elements for which average is to calculate and store user given input into variable called ‘n’.

Step2: Create empty list with name ‘list1’.

Step3: Use for loop ‘n’ times to get user input.

Step4: Use input function and get integer input from user and store in ‘element’ variable.

Step5: Append user input every time in the list1.

Step6Use sum function to sum up all the elements present in the list(list1),then divide by elements count(‘n’) and store in ‘average’ variable.

Step7: Print the final result(Average of a given set of numbers)using ‘average’ variable in the ‘print’ function.

n=int(input('number'))  #Step1:
rev=0               #Step2:
#print(n)
while(n>0):         #Step3:
r=n%10          #Step4:
rev=rev*10+r    #Step5:
n=n//10         #Step6:
#print(r,n)
print(rev)          #Step7:

Step1: Get the integer input from user using ‘input’ function.

Step2: Set rev=’0’ for upcoming reference in while loop.

Step3: If the given number is greater than ‘0’,then run following set of instructions, place(n>0) within while loop.

Step4: Retrieve remainder of original number through dividing by 10 to get last digit of number and store in ‘r’ variable.

Step5: Set the last digit into first/expected positions by multiplying rev with 10 and then add by remainder(‘r’) and the same would be stored in ‘rev’ variable.

Step6: Apply floor division(‘//’)to original number to reduce size of entered number and store the same in ‘n’, As the size reduces to ‘0’,pointer comes out of while loop.

Step7: Print the final result stored in ‘rev’ variable.

num=int(input('Enter number?'))         #Step1:
def palindrome(num):                    #Step2:
rev=0                               #Step3:
while(num>0):
rem=num%10
rev=rev*10+rem
num=num//10
return rev

result=palindrome(num)                  #Step4:
print('Reverse of given number:',result)    #Step5:
if(num==result):                        #Step6:
print('Given number is palindrome')
else:
print('Given number is not palindrome')

Step1: Get the integer input from user through ‘input’ function.

Step2: Define the palindrome function and pass user input as parameter.

Step3: Follow the same steps as done to reverse given number in the previous code.

Step4: Call ‘palindrome’ function and returned reverse of given number by function would be stores in ‘result’ variable.

Step5: Print the reverse of entered number, this step is optional for our clarification.

Step6: Use conditional statement(if..else) to check whether original_number==reversed_number, if so then entered number is palindrome else not.

Output1: If number is of type palindrome.

Output2: If number is not of type palindrome.

n=int(input('Enter the number?'))                #Step1:
c=0                                          #Step2:
while(n>0):                                  #Step3:
c=c+1                                    #Step4:
n=n//10                                  #Step5:
print('Number of digits in the given number:',c) #Step6:
result would be populated using print function.

Step1: Get the input from user.

Step2: Set the count_variable ‘c’ as ‘0’.

Step3: Repeat the while loop until entered number greater than ‘0’(n>0),once n==0 the pointer comes out of loop.

Step4: As loop repeats the count_variable would increment(c=c+1).

Step5: Everytime number of digits in the given number would be decremented by applying ‘Floor Division’(n//10).

Step6: As the pointer comes out of loop,the final result would be populated using ‘print’ function.

Output:

num=int(input('Enter the number?'))                 #Step1:
f=num//2                                            #Step2:
if(num>1):                                          #Step3:
for i in range(2,f+1):                          #Step5:
if(num%i==0):                               #Step6:
print('The given number is not prime')
break
else:                                           #Step7
print('Given number is prime')
else:                                               #Step4:
print('1 is not a prime number')
print(‘Given number is less than or equal to 1 then it cant be prime')

Step1: Get the integer input from user and store in variable ‘num’.

Step2: Calculate half of user_input(num//2) using ‘Floor division’ and store the same in variable ‘f’ for upcoming reference in the code.

Step3: Use conditional statement to check whether number is >1 or not,If(num>!) then check for number is prime or not.

Step4: If(num<=1) then number can’t be prime, the same message is to display using ‘print’ statement.

Step5: Use for loop within conditional statement(if num>1)to check whether entered number is prime or not and iterate for loop from 2 to num//2+1(f+1) times.

Step6: Apply modulo operation between user_input(num) and numbers generated from for loop(2 to f+1),In any of single case if(num%i==0) then entered number is not prime thus ‘break the execution’ and ‘print that number is not prime’.

Step7: Otherwise if(num%i!=0) then ‘Given number is prime’ as given in the ‘else’ statement.

Output1: If user entered input is prime

Output2: If user entered input is not prime

Output3: If user entered input is 0 or 1,then msg should be as not prime

#An Armstrong number is a number such that the sum of its digits raised to the third power is equal to the number itself.
#Samples:153,370,371,407
num=int(input('Enter number?'))                              #Step1:

def Armstrong(num):                                          #Step2:
list_int=list(map(int,str(num)))
#print('List elements are:',list_int)
list_new =[]                                            #Step3:
for i in list_int:                                      #Step4:
list_new.append(i**3)                               #Step5:
sum_cubes=sum(list_new)                                 #Step6:
#print('Sum of cubes of entered number:',sum_cubes)
return sum_cubes

result=Armstrong(num)                                       #Step7:
print(result)
if(num==result):                                            #Step8:
print('Given number is armstrong')
else:
print('Given number is not armstrong')

Step1: Get the input from user and store in ‘num’.

Step2: Define Armstrong function and pass the user input(num) as parameter.

Step3: Create empty list with name ‘list_new’.

Step4: Use for loop to retrieve cubes of digits of entered number(num).

Step5: Use append function and add the cubes of digits of user input into ‘list_new’.

Step6: Use sum function to sum up cubes of digits of user input and return the same.

Step7: Create function call to ‘Armstrong’ function and pass user input as parameter, Once the execution of function call is successful the returned result would be stored in variable called ‘result’.

Step8: If the user input is equal to result obtained after processing ‘Armstrong’ function, then the entered number is armstrong else not.

Output1: If the user input is Armstrong number

Output2: If user input is not Armstrong number

nput1=input('Enter elements for list1?')                   #Step1:
list1=input1.split()
#print(list1)

input2=input('Enter elements for list2?')
list2=input2.split()
#print(list2)
list3=list(set(list1)&set(list2))                           #Step2:
list_common=[]                                              #Step3:
for i in list3:                                             #Step4:
list_common.append(i)                                   #Step5:
print('Common elements among 2 lists are:',list_common)

Step1: Get the 2 sets of inputs from user in the form of list, using ‘split’ function and store the same into ‘list1’ and ‘list2’.

Step2: Convert inputs from list to set form to remove duplicate elements from list, then apply ‘and operation(&)’ to retrieve common elements between 2 sets and at the end again convert them back to list form for our convenience.

Step3: Create empty list with name ‘list_common’ for upcoming use.

Step4: Iterate for loop through list3(which contain common elements of list1,list2)

Step5: Store the common elements in the form list into ‘list_common’ and populate the same to user using ‘print’ function.

Output:

string=input('Enter the string?')                           #Step1:
#print(string)
vc=0                                                        #Step2:
cc=0
for i in string:                                            #Step3:
#print(i)
if(i=='a' or i=='e'or i=='i' or i=='o' or i=='u' or     #Step4:
i=='A' or i=='E' or i=='I' or i=='O' or i=='U'):
vc=vc+1
elif(i==' '):                                           #Step5:
continue
else:
cc=cc+1                                            #Step6:
print('Number vowels in the given string:',vc)              #Step7:
print('Number of consonants in the given string:',cc)

Step1: Enter the string input and store in variable ‘string’.

Step2: Set the variables vc and cc as ‘0’(initial count for number of vowels and consonants in the string).

Step3: Use for loop to iterate over letters of the string.

Step4: Use conditional statement(if..elif..else),if letter(i)==a,e,i,o,u or A,E,I,O,U then increment vowels count(vc),else move to next set of instructions.

Step5: If there is ‘whitespace’ in between string letters, then to ignore that portion use ‘continue’ statement in the code.

Step6: If the above 2 conditions not satisfied then consonants count(cc) would be incremented.

Step7: Print the obtained result from vc,cc using ‘print’ function.

Output:

while True:                                 #Step1:
str=input('Enter the string?')          #Step2:
str_rev=str[::-1]                       #Step3:
print('Reversed string is:',str_rev)    #Step4:
if(str==str_rev):                       #Step5:
print('Given string is palindrome')
break
else:                                   #Step6:
print('Given string is not palindrome')

Step1: Use the ‘while’ loop to ensure user entered correct input(means palindromic string),otherwise repeat the loop until user enters palindromic string.

Step2: Enter the string input and store the same in ‘str’.

Step3: Use str[::-1] code to reverse entered string and store in the variable ‘str_rev’.

Step4: Print the reversed string(str_rev),But this step is optional for our clarification.

Step5: Use conditional statement(if..else),if ‘original string(str)’ is same as ‘reversed string(str_rev)’,then print string as ‘palindrome’ and stop the execution of outer while loop using ‘break’ statement.

Step6: If the above instructions are not true, then string is not palindrome.

Output:

list=[1,2,3,4]                                          #Step1:
n=len(list)                                             #Step2:
print('original list:',list)                            #Step3:
temp=list[0]                                            #Step4:
list[0]=list[n-1]
list[n-1]=temp
print('list aftr swapping 1st and last element:',list)  #Step5:

Step1: Take the valid list.

Step2: Store the size of list into variable ‘n’.

Step3: Print the original list, this step is optional for our convenience.

Step4: Apply the swapping instructions using temp,first and last element of the list.

Step5: Print the updated list after swapping of first and last elements.

Output:

## Description

Python has turned out to be the most in-demand programming language in recent years. Many IT  companies that hunt for good Python programmers are ready to pay the best salaries to the eligible candidates. Hence, we have covered the top commonly asked Python interview questions to familiarize you with the knowledge and skills required to succeed in your next Python job interview.

It's time to view what companies use Python. Companies like Google, Facebook, Netflix etc uses Python. Among programming languages, Python is the most promising career option for techies. Companies today, both in India and the US, are looking out for the qualified and skilled workforce to meet the needs of customers. Python, SQL, Java, JavaScript, .NET, C, C#, AngularJS, C++, PHP, ReactJS, Android, iOS, Ruby, NodeJS, Go, and Perl is some of the hot skills that will help you rock for 2019 and beyond. According to GitHub and Stack Overflow, taking up Python training  will be an added advantage. A Python Developer will earn an average of 4,41,248  per year.

Interviews can be scary, but preparing these Python interview questions will help you in pursuing your dream career. It’s important to be prepared to respond effectively to the questions that employers typically ask in an interview. Since these interview questions on Python are very common, your prospective recruiters will expect you to be able to answer. These Python interview questions and answers will increase your confidence that you need to ace the interview and motivation as well.

Going through these Python programming interview questions will help you to land your dream job in Data Science, Machine Learning or just Python coding. These Python basic interview questions will surely boost your confidence to face an interview and will definitely prepare you to answer the toughest of questions in the best way possible. These Python developer interview questions are suggested by experts and have proven to have great value.

Not only the job aspirants but also the recruiters can also refer these Python basic interview questions to know the right set of questions to assess a candidate.

Treat your next Python interview as an entrance to success. Give it your best and get the job. Wish you all the luck and confidence.