All Python Interview Questions

What is Python?

Python is a high-level, general-purpose programming language that is easy to read and write. It was created by Guido van Rossum and first released in 1991.

People use Python for web development, data analysis, automation, machine learning and scripting. The syntax is close to plain English, so it is a popular first language for beginners.

print("Hello, Python!")

Output:

Tutorials Class - Output Window

Hello, Python!

Python supports more than one style of programming, such as procedural, object-oriented and functional. It also comes with a big standard library, so many common tasks need very little code. To start learning, read the Python Introduction chapter.

Is Python an interpreted language?

Python is usually called an interpreted language, but the full story has two steps. First, Python compiles your source code into a lower-level form called bytecode. Then the Python Virtual Machine (PVM) runs that bytecode one instruction at a time.

You do not need to run a separate compile command. Python does both steps for you when you run the file. The bytecode is often saved in a __pycache__ folder so the next run can start faster.

python hello.py

That one command compiles and runs the program. Because of this, you can change a file and run it again straight away, which is why Python feels quick for learning and testing. Read the next question to understand what an interpreted language is.

What is an interpreted language?

An interpreted language is a language where a program called an interpreter reads the code and runs it step by step, instead of first turning the whole program into machine code. Python, JavaScript, PHP and Ruby are common examples.

A compiled language such as C or C++ is converted into a machine code file before it runs. Then the computer runs that file directly.

PointInterpretedCompiled
How it runsInterpreter runs the code step by stepWhole program is converted first, then run
SpeedUsually slowerUsually faster
ErrorsFound when that line runsMany errors found before the program runs
ExamplesPython, PHP, JavaScriptC, C++, Go

The line is not always sharp. Python, for example, also compiles code to bytecode first (see Is Python an interpreted language?).

What is PEP 8?

PEP 8 is the official style guide for Python code. PEP stands for Python Enhancement Proposal. It was first written in 2001 and gives simple rules so that everyone writes Python in a similar, readable way.

  • Use 4 spaces for each indentation level, not tabs.
  • Keep lines up to 79 characters.
  • Use snake_case for variables and functions, and CapWords for class names.
  • Put spaces around operators and after commas.
  • Leave two blank lines between top-level functions and classes.
# Not PEP 8 style
def AddNumbers(a,b):
  return a+b
x=AddNumbers(2,3)

# PEP 8 style
def add_numbers(a, b):
    return a + b


total = add_numbers(2, 3)

Both versions work, but the second one is easier to read. Tools like flake8 and black can check or fix the style automatically.

What is a list in Python?

A list is an ordered, changeable collection of items written inside square brackets [ ]. A list can hold items of different types and it allows duplicate values.

fruits = ["apple", "banana", "cherry"]
fruits.append("mango")

print(fruits)
print(fruits[0])
print(len(fruits))

Output:

Tutorials Class - Output Window

['apple', 'banana', 'cherry', 'mango']
apple
4

Items are numbered from 0, so fruits[0] is the first item. Because a list is mutable, you can add, remove or change items after creating it. Learn more in the Python Lists chapter.

What is a tuple in Python?

A tuple is an ordered collection of items written inside round brackets ( ). Unlike a list, a tuple is immutable, which means you cannot change, add or remove its items after it is created.

colors = ("red", "green", "blue")
print(colors[1])

colors[1] = "black"

Output:

Tutorials Class - Output Window

green
Traceback (most recent call last):
File "main.py", line 4, in <module>
colors[1] = "black"
TypeError: 'tuple' object does not support item assignment

Tuples are good for data that should not change, like a point (10, 20) or days of the week. A tuple with one item needs a comma, like ("apple",). See the Python Tuples chapter for more.

What is a set in Python?

A set is an unordered collection of unique items written inside curly braces { }. It has no index, and if you add a duplicate value, Python simply ignores it.

nums = {1, 2, 2, 3, 3}
print(nums)

a = {1, 2, 3}
b = {3, 4}
print(a | b)   # union
print(a & b)   # common items

Output:

Tutorials Class - Output Window

{1, 2, 3}
{1, 2, 3, 4}
{3}

Sets are useful to remove duplicates from data and to check membership quickly. To create an empty set use set(), because {} makes an empty dictionary. More in the Python Sets chapter.

What is a dictionary in Python?

A dictionary stores data as key: value pairs inside curly braces { }. You use the key to get the value. Keys must be unique, and from Python 3.7 a dictionary also remembers the order in which items were added.

student = {"name": "Robin", "age": 20}

print(student["name"])
student["city"] = "Delhi"
print(student)
print(student.get("phone", "not found"))

Output:

Tutorials Class - Output Window

Robin
{'name': 'Robin', 'age': 20, 'city': 'Delhi'}
not found

Using get() is safer than square brackets, because it does not raise a KeyError when the key is missing. See the Python Dictionary chapter for more methods.

What are the key features of Python?

The main features of Python are its simple syntax, a big standard library and the freedom to write code in more than one style.

  • Easy to learn: the syntax is short and close to English.
  • Interpreted: code is run directly, so you can test small pieces quickly.
  • Dynamically typed: you do not declare the type of a variable.
  • Object-oriented: supports classes and objects, and also procedural and functional styles.
  • Large standard library: modules for files, dates, math, web and more.
  • Free and open source: anyone can download and use it.
  • Cross-platform: the same code runs on Windows, macOS and Linux.

Read the Python Introduction chapter to see these features in action.

Is Python case-sensitive?

Yes, Python is case-sensitive. This means name, Name and NAME are three different identifiers. The same is true for keywords: True works, but true does not.

name = "Robin"
print(Name)

Output:

Tutorials Class - Output Window

Traceback (most recent call last):
File "main.py", line 2, in <module>
print(Name)
NameError: name 'Name' is not defined. Did you mean: 'name'?

A wrong capital letter is one of the most common mistakes for beginners, so check the spelling first when you see a NameError. The “Did you mean” hint is shown by Python 3.10 and above. See Python Variables for naming rules.

How would you convert a string into lowercase?

Use the lower() method. It returns a new string with all letters in lowercase. The original string does not change, because strings in Python are immutable.

text = "Hello World"
print(text.lower())
print(text)

Output:

Tutorials Class - Output Window

hello world
Hello World

To change the case the other way, see how to convert a string into uppercase. A common use of lower() is to compare two strings without worrying about capital letters.

How would you convert a string into uppercase?

Use the upper() method. It returns a new string with all letters in capital. Like all string methods, it does not change the original string.

name = "david smith"
print(name.upper())
print(name.title())
print(name.capitalize())

Output:

Tutorials Class - Output Window

DAVID SMITH
David Smith
David smith

title() makes the first letter of every word a capital, and capitalize() changes only the first letter of the whole string. The opposite of upper() is lower(), explained in this question.

What is the use of the input() function in Python?

The input() function takes data typed by the user from the keyboard. The program stops and waits until the user presses Enter, and then the value is returned as a string.

name = input("Enter your name: ")
print("Hello,", name)

age = int(input("Enter your age: "))
print("Next year you will be", age + 1)

Output:

Tutorials Class - Output Window

Enter your name: Robin
Hello, Robin
Enter your age: 20
Next year you will be 21

Remember that input() always gives a string, even if the user types a number. Use int() or float() to convert it before doing maths. Read more in the Python input() Function chapter.

Why do we use the join() function in Python?

The join() method joins all the items of a list, tuple or other iterable into one string. The string you call it on is used as the separator between the items.

words = ["Learn", "Python", "Fast"]

print(" ".join(words))
print("-".join(words))
print("".join(words))

Output:

Tutorials Class - Output Window

Learn Python Fast
Learn-Python-Fast
LearnPythonFast

All items must be strings. If the list has numbers, you get a TypeError, so convert them first.

numbers = [1, 2, 3]
print(",".join(str(n) for n in numbers))

Output:

Tutorials Class - Output Window

1,2,3

join() is also faster than adding many strings with + in a loop.

What is a negative index in Python and why is it used?

A negative index counts from the end of a sequence. -1 is the last item, -2 is the second last, and so on. Positive indexes start from 0 at the front.

letters = ["a", "b", "c", "d"]
print(letters[-1])
print(letters[-2])

text = "Python"
print(text[-3:])
print(text[:-1])

Output:

Tutorials Class - Output Window

d
c
hon
Pytho

It is useful because you can get the last items without knowing the length of the list. A common use is text[:-1] to remove the last character, for example a new-line at the end of a line. If the negative number is bigger than the length, Python raises an IndexError.

What is a docstring in Python?

A docstring is a string written in triple quotes as the first statement of a function, class or module. It explains what that code does.

def add(a, b):
    """Return the sum of a and b."""
    return a + b

print(add.__doc__)

Output:

Tutorials Class - Output Window

Return the sum of a and b.

A docstring is different from a comment. A comment (starting with #) is ignored by Python, but a docstring is stored with the object. You can read it with __doc__ or with the help() function. See Python Comments for more.

What is the use of self in Python?

self is the first parameter of a method in a class. It refers to the current object, so the method can reach the attributes and other methods of that object. Python passes it automatically when you call the method.

class Student:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print("Hi, I am", self.name)

s = Student("Robin")
s.greet()

Output:

Tutorials Class - Output Window

Hi, I am Robin

self is not a keyword. You could use another name, but everyone uses self, so please do the same. Learn more in Python Classes and Objects.

What is scope in Python?

Scope is the part of a program where a variable can be used. Python looks for a name in four places, in this order, which is called the LEGB rule.

ScopeMeaning
LocalNames created inside the current function
EnclosingNames in an outer function that wraps the current one
GlobalNames created at the top level of the file
Built-inNames Python already has, like len and print
x = "global"

def outer():
    x = "enclosing"

    def inner():
        x = "local"
        print(x)

    inner()
    print(x)

outer()
print(x)

Output:

Tutorials Class - Output Window

local
enclosing
global

Use the global keyword to change a global variable inside a function, and nonlocal for a variable of the outer function. See Scope of Variables in Python.

What is the use of help() and dir() in Python?

Both are built-in functions that help you explore Python from the console. help() shows the documentation of a function, class or module. dir() shows a list of the names (attributes and methods) that an object has.

def greet(name):
    """Print a greeting."""
    print("Hi", name)

help(greet)

Output:

Tutorials Class - Output Window

Help on function greet in module __main__:

greet(name)
Print a greeting.

items = [3, 1, 2]
print("append" in dir(items))
print("upper" in dir(items))

Output:

Tutorials Class - Output Window

True
False

So dir() answers “what can I do with this object?” and help() answers “how do I use it?”. The text shown by help() comes from the docstring.

What is a lambda function in Python?

A lambda function is a small function without a name (an anonymous function) that is written in a single line using the lambda keyword. The syntax is lambda arguments: expression, and the value of the expression is returned automatically.

square = lambda x: x * x
add = lambda a, b: a + b

print(square(5))
print(add(2, 3))

names = ["Robin", "Al", "Maria"]
print(sorted(names, key=lambda n: len(n)))

Output:

Tutorials Class - Output Window

25
5
['Al', 'Robin', 'Maria']

Lambdas are mostly used for short, one-time work, like the key of sorted() or inside map() and filter(). For anything longer, a normal def function is easier to read. See Python Lambda for more.