Top 30 Python Interview Questions and Answers

1. Python Interview Questions and Answers

Welcome to our Python Interview Questions and answers series. Today, we will look at some more interview questions for Python, some basic to advanced interview questions to help you to prepare for your interview. There are Python coding interview questions, Python developer interview questions Python scripting interview question as well as Data structure interview questions. In case you missed Python Interview Questions Part I, check it out.
So, let’s begin Interview Questions of Python Programming Language.
If you can DREAM it, you can ACHIEVE it.

Python interview Questions

Python interview Questions

Q.1. What data types does Python support?

This is the most basic python interview question.

Python provides us with five kinds of data types:

  • Numbers- Numbers use to hold numerical values.
>>> a=7.0
  • Strings- A string is a sequence of characters.  We declare it using single or double quotes.
>>> title="Ayushi's Book"
  • Lists- A list is an ordered collection of values, and we declare it using square brackets.
>>> colors=['red','green','blue']
>>> type(colors)

<class ‘list’>

  • Tuples- A tuple, like a list, is an ordered collection of values. The difference. However, is that a tuple is immutable. This means that we cannot change a value in it.
Python Interview Questions and Answers

Python Interview Questions and Answers – Python Data Types

>>> name=('Ayushi','Sharma')
>>> name[0]='Avery'

Traceback (most recent call last):
File “<pyshell#129>”, line 1, in <module>
TypeError: ‘tuple’ object does not support item assignment

  1. Dictionary- A dictionary is a data structure that holds key-value pairs. We declare it using curly braces.
>>> squares={1:1,2:4,3:9,4:16,5:25}
>>> type(squares)

<class ‘dict’>

>>> type({})

<class ‘dict’>
We can also use a dictionary comprehension:

>>> squares={x:x**2 for x in range(1,6)}
>>> squares

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Follow this link to know more about Python Data Structure

Q.2. What is a docstring?

A docstring is a documentation string that we use to explain what a construct does. We place it as the first thing under a function, class, or a method, to describe what it does. We declare a docstring using three sets of single or double quotes.

>>> def sayhi():
    The function prints Hi
>>> sayhi()


To get a function’s docstring, we use its __doc__ attribute.

>>> sayhi.__doc__

‘\n\tThis function prints Hi\n\t’

A docstring, unlike a comment, is retained at runtime.

Q.3. What is the PYTHONPATH variable?

PYTHONPATH is the variable that tells the interpreter where to locate the module files imported into a program. Hence, it must include the Python source library directory and the directories containing Python source code. You can manually set PYTHONPATH, but usually, the Python installer will preset it.

2. Basic Python Interview Questions

Q.4. What is slicing?

These are the types of basic Python interview questions for freshers.
Slicing is a technique that allows us to retrieve only a part of a list, tuple, or string. For this, we use the slicing operator [].

>>> (1,2,3,4,5)[2:4]

(3, 4)

>>> [7,6,8,5,9][2:]
[8, 5, 9]
>>> 'Hello'[:-1]


Q.5. What is a namedtuple?

A namedtuple will let us access a tuple’s elements using a name/label. We use the function namedtuple() for this, and import it from collections.

>>> from collections import namedtuple
>>> result=namedtuple('result','Physics Chemistry Maths') #format
>>> Ayushi=result(Physics=86,Chemistry=95,Maths=86) #declaring the tuple
>>> Ayushi.Chemistry


As you can see, it let us access the marks in Chemistry using the Chemistry attribute of object Ayushi.

To learn more about namedtuples, refer to namedtuple in Python.

Q.6. How would you declare a comment in Python?

Unlike languages like C++, Python does not have multiline comments. All it has is octothorpe (#). Anything following a hash is considered a comment, and the interpreter ignores it.

>>> #line 1 of comment
>>> #line 2 of comment

In fact, you can place a comment anywhere in your code. You can use it to explain your code.

Q.7. How would you convert a string into an int in Python?

If a string contains only numerical characters, you can convert it into an integer using the int() function.

>>> int('227')


Let’s check the types:

>>> type('227')

<class ‘str’>

>>> type(int('227'))

 <class ‘int’>

Q.8. How do you take input in Python?

For taking input from user, we have the function input(). In Python 2, we had another function raw_input().

The input() function takes, as an argument, the text to be displayed for the task:

>>> a=input('Enter a number')

Enter a number7

But if you have paid attention, you know that it takes input in the form of a string.

>>> type(a)

<class ‘str’>

Multiplying this by 2 gives us this:

>>> a*=2
>>> a


So, what if we need to work on an integer instead?

We use the int() function for this.

>>> a=int(input('Enter a number'))

Enter a number7

Now when we multiply it by 2, we get this:

>>> a*=2
>>> a


Q.9. What is a frozen set in Python?

Answer these type of Python Interview Questions with Examples.

First, let’s discuss what a set is. A set is a collection of items, where there cannot be any duplicates. A set is also unordered.

>>> myset={1,3,2,2}
>>> myset

{1, 2, 3}

This means that we cannot index it.

>>> myset[0]

Traceback (most recent call last):
File “<pyshell#197>”, line 1, in <module>
TypeError: ‘set’ object does not support indexing

However, a set is mutable. A frozen set is immutable. This means we cannot change its values. This also makes it eligible to be used as a key for a dictionary.

>>> myset=frozenset([1,3,2,2])
>>> myset

frozenset({1, 2, 3})

>>> type(myset)

<class ‘frozenset’>

For more insight on sets, refer to Python Sets and Booleans.

Q.10. How would you generate a random number in Python?

This kind of Python interview Questions and Answers can Prove your depth of knowledge.

To generate a random number, we import the function random() from the module random.

>>> from random import random
>>> random()


Let’s call for help on this.

>>> help(random)

Help on built-in function random:

random(…) method of random.Random instance
random() -> x in the interval [0, 1).

This means that it will return a random number equal to or greater than 0, and less than 1.

We can also use the function randint(). It takes two arguments to indicate a range from which to return a random integer.

>>> from random import randint
>>> randint(2,7)


>>> randint(2,7)


>>> randint(2,7)


>>> randint(2,7)


>>> randint(2,7)


Q.11. How will you capitalize the first letter of a string?

Simply using the method capitalize().

>>> 'ayushi'.capitalize()


>>> type(str.capitalize)

<class ‘method_descriptor’>

However, it will let other characters be.

>>> '@yushi'.capitalize()


Q.12. How will you check if all characters in a string are alphanumeric?

For this, we use the method isalnum().

>>> 'Ayushi123'.isalnum()


>>> 'Ayushi123!'.isalnum()


Other methods that we have include:

>>> '123.3'.isdigit()


>>> '123'.isnumeric()


>>> 'ayushi'.islower()


>>> 'Ayushi'.isupper()


>>> 'Ayushi'.istitle()


>>> '   '.isspace()


>>> '123F'.isdecimal()


Q.13. What is the concatenation?

This is very basic Python Interview Question, try not to make any mistake in this.

Concatenation is joining two sequences. We use the + operator for this.

>>> '32'+'32'


>>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]
>>> (2,3)+(4)

Traceback (most recent call last):
File “<pyshell#256>”, line 1, in <module>
TypeError: can only concatenate tuple (not “int”) to tuple

Here, 4 is considered an int. Let’s do this again.

>>> (2,3)+(4,)

(2, 3, 4)

Any query yet in basic Python interview questions and answers for freshers? Please Comment.

Q.14. What is a function?

When we want to execute a sequence of statements, we can give it a name. Let’s define a function to take two numbers and return the greater number.

>>> def greater(a,b):
       return a is a>b else b
>>> greater(3,3.5)


You can create your own function or use one of Python’s many built-in functions.

Q.15. Explain lambda expressions. When would you use one?

When we want a function with a single expression, we can define it anonymously. A lambda expression may take input and returns a value. To define the above function as a lambda expression, we type the following code in the interpreter:

>>> (lambda a,b:a if a>b else b)(3,3.5)


Here, a and b are the inputs. a if a>b else b is the expression to return. The arguments are 3 and 3.5.
It is possible to not have any inputs here.

>>> (lambda :print("Hi"))()


For more insight into lambdas, refer to Lambda Expressions in Python.

Q.16. What is recursion?

When a function makes a call to itself, it is termed recursion. But then, in order for it to avoid forming an infinite loop, we must have a base condition.

Let’s take an example.

>>> def facto(n):
    if n==1: return 1
    return n*facto(n-1)
>>> facto(4)


For more on recursion, visit Recursion in Python.

Q.17. What is a generator?

Python generator produces a sequence of values to iterate on. This way, it is kind of an iterable.

We define a function that ‘yields’ values one by one, and then use a for loop to iterate on it.

>>> def squares(n):
        yield i**2
>>> for i in squares(7):


Q.18. So, what is an iterator, then?

An iterator returns one object at a time to iterate on. To create an iterator, we use the iter() function.

Then, we call the next() function on it every time we want an object.

>>> next(odds)


>>> next(odds)


>>> next(odds)


>>> next(odds)


>>> next(odds)

And now, when we call it again, it raises a StopIteration exception. This is because it has reached the end of the values to iterate on.

>>> next(odds)

Traceback (most recent call last):
File “<pyshell#295>”, line 1, in <module>

For more on iterators, refer to Python iterators.

Q.19. Okay, we asked you about generators and iterators, and you gave us the right answers. But don’t they sound similar?

They do, but there are subtle differences:

  1. For a generator, we create a function. For an iterator, we use in-built functions iter() and next().
  2. For a generator, we use the keyword ‘yield’ to yield/return an object at a time.
  3. A generator may have as many ‘yield’ statements as you want.
  4. A generator will save the states of the local variables every time ‘yield’ will pause the loop. An iterator does not use local variables; it only needs an iterable to iterate on.
  5. Using a class, you can implement your own iterator, but not a generator.
  6. Generators are fast, compact, and simpler.
  7. Iterators are more memory-efficient.

Read Generators vs Iterators in Python.

Q.20. We know Python is all the rage these days. But to be truly accepting of a great technology, you must know its pitfalls as well. Would you like to talk about this?

Of course. To be truly yourself, you must be accepting of your flaws. Only then can you move forward to work on them. Python has its flaws too:

  1. Python’s interpreted nature imposes a speed penalty on it.
  2. While Python is great for a lot of things, it is weak in mobile computing, and in browsers.
  3. Being dynamically-typed, Python uses duck-typing (If it looks like a duck, it must be a duck). This can raise runtime errors.
  4. Python has underdeveloped database access layers. This renders it a less-than-perfect choice for huge database applications.
  5. And then, well, of course. Being easy makes it addictive. Once a Python-coder, always a Python coder.

So while it has problems, it is also a wonderful tool for a lot of things. Refer to Python Advantages and Disadvantages.

Python Interview Questions

3. Python Interview Questions for Experienced

These are the Advanced Python Interview Questions and Answers for Experienced, however they can also refer the basic Python Interview Questions and Answers for Freshers for basic knowledge.

Q.21. What does the function zip() do?

One of the less common functions with beginners, zip() returns an iterator of tuples.

>>> list(zip(['a','b','c'],[1,2,3]))
[(‘a’, 1), (‘b’, 2), (‘c’, 3)]

Here, it pairs items from the two lists, and creates tuples with those. But it doesn’t have to be lists.

>>> list(zip(('a','b','c'),(1,2,3)))
[(‘a’, 1), (‘b’, 2), (‘c’, 3)]

Q.22. If you are ever stuck in an infinite loop, how will you break out of it?

For this, we press Ctrl+C. This interrupts the execution. Let’s create an infinite loop to demonstrate this.

>>> def counterfunc(n):
>>> counterfunc(7)

Traceback (most recent call last):
File “<pyshell#332>”, line 1, in <module>
File “<pyshell#331>”, line 2, in counterfunc


Any doubt yet in Python Advanced interview Questions? Please comment.

Q.23. Explain Python’s parameter-passing mechanism.

To pass its parameters to a function, Python uses pass-by-reference. If you change a parameter within a function, the change reflects in the calling function. This is its default behavior. However, when we pass literal arguments like strings, numbers, or tuples, they pass by value. This is because they are immutable.

Q.24. With Python, how do you find out which directory you are currently in?

To find this, we use the function/method getcwd(). We import it from the module os.

>>> import os
>>> os.getcwd()


>>> type(os.getcwd)

<class ‘builtin_function_or_method’>

We can also change the current working directory with chdir().

>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>> os.getcwd()


For more on this, read up on Python Directory.

Q.25. How will you find, in a string, the first word that rhymes with ‘cake’?

For our purpose, we will use the function search(), and then use group() to get the output.

>>> import re
>>>'.ake','I would make a cake, but I hate to bake')


And as we know, the function search() stops at the first match. Hence, we have our first rhyme to ‘cake’.

Q.26. How would you display a file’s contents in reversed order?

Let’s first get to the Desktop. We use the chdir() function/method form the os module for this.

>>> import os
>>> os.chdir('C:\\Users\\lifei\\Desktop')

The file we’ll use for this is Today.txt, and it has the following contents:
HTML, CSS, jQuery, JavaScript
Python, C++, Java
This sem’s subjects

Let’s read the contents into a list, and then call reversed() on it:

>>> for line in reversed(list(open('Today.txt'))):


This sem’s subjects

Python, C++, Java

HTML, CSS, jQuery, JavaScript


Without the rstrip(), we would get blank lines between the output.

Q.27. What is Tkinter?

Tkinter is a famous Python library with which you can craft a GUI. It provides support for different GUI tools and widgets like buttons, labels, text boxes, radio buttons, and more. These tools and widgets have attributes like dimensions, colors, fonts, colors, and more.

You can also import the tkinter module.

>>> import tkinter
>>> top=tkinter.Tk()

This will create a new window for you:

This creates a window with the title ‘My Game’. You can position your widgets on this.

Follow this link to know more about Python Libraries

Q.28. How is a .pyc file different from a .py file?

While both files hold bytecode, .pyc is the compiled version of a Python file. It has platform-independent bytecode. Hence, we can execute it on any platform that supports the .pyc format. Python automatically generates it to improve performance(in terms of load time, not speed).

Q.29. How do you create your own package in Python?

We know that a package may contain sub-packages and modules. A module is nothing but Python code.

To create a package of our own, we create a directory and create a file in it. We leave it empty. Then, in that package, we create a module(s) with whatever code we want. For a detailed explanation with pictures, refer to Python Packages.

Q.30. How do you calculate the length of a string?

This is simple. We call the function len() on the string we want to calculate the length of.

>>> len('Ayushi Sharma')


4. Conclusion

So here in Python interview questions and answers, we discussed some more questions. But hold on, this isn’t all.
If you have any query in Python Interview answers or questions, Please comment.

See you in Part III.

1 Response

  1. Sethumadhava says:

    Good information gathered nice to learn and attend the interviews for Freshers as well as exp.

    Thank You so much

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.