Jose Portilla

Python is a versatile, general-purpose programming language. It is also one of the most popular programming languages in use today. Companies large and small use it across industries, including Google. Knowledge of Python will open many doors and career opportunities.

Answering the Python interview questions can be daunting. You may know how to write Python code. You may even know how to create full-scale Python applications, but sometimes the questions can be tricky. To help you prepare for your next Python job interview or just refresh your knowledge of the Python programming language, we have compiled a list of questions you might run into at your next interview.

2021 Complete Python Bootcamp From Zero to Hero in Python

Last Updated January 2021

  • 155 lectures
  • All Levels
4.6 (351,059)

Learn Python like a Professional Start from the basics and go all the way to creating your own applications and games | By Jose Portilla

Explore Course

1.What type of language is Python?

Python is a general-purpose, object-oriented language. It is also an interpreted language.

2. What are some features of the Python language?

•      Python is an interpreted language, meaning that Python code does not need to compile before running.

•      Python is a dynamically typed language. This means you don’t need to declare the type of variable when you create it. Python will determine its type dynamically.

•      Python is object-oriented. With Python, you can define classes and use composition and inheritance. Python does not support access specifiers like public and private.

•      Functions in Python are first-class objects. This means that you can assign them to a variable. Python functions can also return other functions or accept them as parameters.

•      Python is a general-purpose language, which is very popular in many industries. Developers use it in automation, web applications, machine learning, big data, and more.

•      It is easy and quick to write code in Python, but Python code generally runs slower than compiled languages.

3. What is PEP8?

PEP8 is the latest set of Python coding standards. It is a document that provides guidelines and best practices for how to write Python code. Its primary focus is to improve the readability and consistency of Python code.

4. What is the difference between a list and a tuple in Python?

Both lists and tuples can store an ordered array of objects, however, a tuple is immutable. This means that once a tuple is created with objects in it, the objects can not be swapped out (mutating). A list still allows for objects to be reassigned within the list.

5. How does Python manage memory?

Python manages memory in the Python private heap space. Pythons memory manager and garbage collector control the private heap space. There are multiple levels of scope that can be used in conjunction with namespace, including Built-In, Global, Enclosed, and Local.

6. What is a Python namespace?

Namespaces in Python ensure that Python variables, functions, and other names don’t clash.

7. What is the purpose of the PYTHONPATH variable?

PYTHONPATH is an environmental variable that will tell the operating system where to find Python libraries. This will ensure that your Operating System calls the correct installation of Python on the computer.

8. What is the purpose of the PYTHONSTARTUP variable?

This variable contains the path of an initialization file that houses Python source code. It executes each time the Python interpreter starts.

9. What is the purpose of the PYTHONCASEOK variable?

This is a variable specifically for running Python on the Windows operating system. It tells the Python interpreter to use case-insensitive match when trying to find imported libraries.

10. What is the purpose of the PYTHONHOME variable?

This is an alternate path to search for Python modules.

11. What are Python modules?

You can consider a Python module as a code library. A module is a collection of Python classes, functions, and variables. Modules are usually separated from each other when they supply different functionality.

12. What are some common modules in the Python standard library?

You will use some of these modules that are included in the Python standard library often when programming in Python:

•      Email: Used to parse, handle, and generate email messages.

•      String: An index of types of strings, such as all capital or lowercase letters.

•      Sqlite3: Used to deal with the SQLite database.

•      XML: Provides XML support.

•      Logging: Creates logging classes to log system details.

•      Traceback: Allows you to extract and print stack trace details.

13. What is scope in Python?

All objects in Python have a scope. Scope is the block of code where the variable is accessible. Here are some scope designations in Python:

•      Local scope: Local objects available in the current function.

•      Global scope: Objects available through the code execution since their inception.

•      Module-level scope: Global objects of the current module accessible in the program.

•      Outermost scope: Built-in names callable in the program.

14. How would you get a user’s home directory (~) in Python?

You can do this with the os module.

import os

This will return the path to the current user’s directory.

15. What built-in types does Python support?

•      Number

•      String

•      Tuple

•      List

•      Dictionary

•      Set

16. What is a Python decorator?

A Python decorator is a function that extends the behavior of another Python function without explicitly modifying it.

17. What is pickling/unpickling in Python?

Pickling is when a Python object converts into a string representation by a pickle module. It is then placed into a file with the dump() function. Unpickling refers to the reverse process, in which the stored string is retrieved and turned back into an object.

18. What is a negative index in Python?

While positive indices begin with position 0 and follow with 1, 2, etc., negative indices end with -1. -2, etc.; -3 is the position before that, and so on. Negative indexes can access elements in a Python list from the end of the list rather than from the beginning.

19. How are global and local variables defined in Python?

In general, variables defined outside of functions are global. Variables defined inside a function can also be made global by using the command global x, for example, to create a global variable called x.

20. Describe a few ways to generate a random number in Python.

Python comes with a variety of techniques to generate random numbers using its Random library:

•      Random(): This command returns a floating-point number between 0 and 1.

•      Uniform(x, y): This command returns a floating-point number between the values given for x and y.

•      Randint(x, y): This command returns a random integer between the values given for x and y.

21. What is a Python dictionary?

A Python dictionary is one of the standard data structures in Python. It is an unordered collection of elements, acting as a hash-table. These elements are stored within key-value pairs. Dictionaries are indexed by keys.

# Python dictionary

dict={'first':'Bob', 'last':'Smith'}

22. Is Python case sensitive?

Yes, Python is a case-sensitive language.

23. What is the output of the following code?

print(var) if var='Hello Everyone!'

The output would be:

Hello Everyone!

24. What is the output of the following code?

print(var[0]) if var='Hello Everyone!'

The output would be:


25. What is the output of the following code?

print(var[2:5])  if var='Hello Everyone!'

The output would be:


26. How would you get all the keys in a Python dictionary?

You would use the dictionary keys function.

dict={'first':'Bob', 'last':'Smith'}

27. How would you get all the values in a Python dictionary?

You would use the dictionary values function.

dict={'first':'Bob', 'last':'Smith'}

28. How do you convert a string to an integer in python?

The Python int function will convert a string to an integer. The second parameter is for the base of the number, so 10 for decimal numbers.

x = '100'
int(x, 10)

29. How do you convert a string to a long in python?

The Python long function will convert a string to a long. The second parameter is for the base of the number, so 10 for decimal numbers.

x = '100'
long(x, 10)

30. How do you convert a string to a floating-point number in python?

The Python float function will convert a string to a floating-point number.

x = '100.12345'

31. How do you convert an object to a string in python?

The Python str function will convert an object to a string.

dict={'first':'Bob', 'last':'Smith'}

32. What does the ** operator do in Python?

The ** operator performs exponential calculations in Python.

# x equals 8

33. What does the // operator do in Python?

The // operator performs floor division. The result will be the whole number in front of the decimal point.

# x equals 2

34. What does the Python is operator do?

When the is operator is used in a Python expression, it evaluates to true if the variables on both sides point to the same object.

## z is true
z=x is y

35. What does the Python not in operator do?

The Python not in operator evaluates to true if it does not find a variable in the specified sequence and false if it does not.

# The following will return true
4 not in [1,2,3]

36. What does the Python break statement do?

The Python break statement stops a loop statement and transfers execution of the code to the statement after the loop.

37. What does the Python continue statement do?

The Python continue statement causes a loop to skip the rest of its body and continue at the beginning of the loop.

38. What does the Python pass statement do?

The Python pass statement is used when a statement is required, but you do not want a command or code to execute.

39. What are Python dictionary and list comprehensions?

Comprehensions in Python are like decorators. They are what is called syntactic sugar that helps create filtered and modified lists and dictionaries from existing lists, dictionaries, or sets. They are handy and quick because you can write them in one line of code.

the_list = [2, 3, 5, 7, 11]

# list comprehension
squared_list = [x**2 for x in the_list]
# output is [4 , 9 , 25 , 49 , 121]

# dict comprehension
squared_dict = {x:x**2 for x in the_list}
# output is {11: 121, 2: 4 , 3: 9 , 5: 25 , 7: 49}

40. What are Python lambdas and why are they used?

Python lambdas are anonymous functions. They can accept multiple arguments but only have a single expression. They are used where a function is needed temporarily and will not be needed by other code. They are also limited in their scope of capabilities compared to a full function.

multiply = lambda x, y : x * y
print(multiply(2, 5))	# outputs 10

41. How do you copy an object in Python?

While the = operator will copy many things in Python, it will not copy a Python object. It only creates a reference to the object. To create a copy of an object in Python, you need to use the copy module. The copy module offers two ways of copying an object.

•      Shallow copy: Copies an object and re-use references from the old object

•      Deep copy: Copies all the values in an object recursively.

from copy import copy, deepcopy

list_1 = [1, 2, [3, 5], 4]

## shallow

list_2 = copy(list_1)
list_2[3] = 11

list_2	# output => [1, 2, [3, 5, 12], 11]
list_1	# output => [1, 2, [3, 5, 12], 4]

## deep

list_3 = deepcopy(list_1)
list_3[3] = 10

list_3	# output => [1, 2, [3, 5, 6, 13], 10]
list_1	# output => [1, 2, [3, 5, 6], 4]

42. What is self in Python?

In Python, self represents the object or instance of a class when referring to itself internally. In other languages, this variable is often called this. In Python classes, you must explicitly pass self as the first parameter in methods.

class Car():
	def __init__(self, model, color):
    	self.model = model
    	self.color = color
	def display(self):
  	  print("Model is", self.model )
    	print("color is", self.color )

43. What is __init__ in Python?

In Python, the __init__ method is used as a constructor for classes. Whenever a new instance of a class is created, __init__ is called first. Constructors are usually used to set up class attributes.

class Car():
	# __init__ sets up the make, model, and color of the car object
	def __init__(self, make, model, color):
    	self.make = make
    	self.model = model
    	self.color = color

44. What is a generator in Python?

Generators in Python are like functions that can return more than once. This is called yielding. They are used to return an iterable collection of items. They are defined with def just like Python functions.

def squares():
  x = range(1, 4) # 1 to 4
	for n in x:
	    yield n**2
for y in squares():
	print(y)   	# prints 1 4 9 16

45. What does the Python help() function do?

The Python help() function will return the documentation of Python modules, classes, functions, etc.

46. What does the Python dir() function do?

The Python dir() function will return a list of methods and attributes from the object you call it with.

47. What is the difference between .py and .pyc files?

Python files that end in the py extension are text-based source files. These are the files you create when writing Python code. Python files with the pyc extension are compiled bytecode files. When a Python application runs, the interpreter looks for existing pyc files. If those do not exist, it then compiles the py source files to bytecode and runs the resulting pyc files.

48. What is a docstring in Python?

A Python docstring is the first comment in the code object. The docstring for the code object is available on that code object’s __doc__ attribute and through the help function.

def the_function():
  """The is a function docstring"""

49. Write Python code to print the complete contents of a file with error handling for missing files.

	with open('filename','r') as file:
except IOError:
	print(“no such file exists”)

50. Write Python code to print the sum of all numbers from 25 to 75, inclusive.


51. Write Python code to print the length of each line in a particular file, not counting whitespace at the ends.

with open('filename.txt', 'r') as file:

52. Write Python code to remove the whitespace from the following string – ‘abc def geh ijk’.

s= ‘abc def geh ijk’.replace(‘ ‘,’’)

53. Write Python code to remove duplicate items from a list.

res = []
[res.append(x) for x in test_list if x not in res]


It pays to prepare for a coding interview. Hopefully, the Python interview questions and answers above will help you brush up on your Python knowledge and give you the confidence you need for your next job interview.

Page Last Updated: February 2021

Top courses in Python

2021 Complete Python Bootcamp From Zero to Hero in Python
Jose Portilla
4.6 (351,059)
Learn Python & Ethical Hacking From Scratch
Zaid Sabih, z Security
4.6 (12,788)
Taming Big Data with Apache Spark and Python - Hands On!
Sundog Education by Frank Kane, Frank Kane
4.5 (10,048)
The Complete Python Course | Learn Python by Doing
Codestars by Rob Percival, Jose Salvatierra, Rob Percival, Teclado by Jose Salvatierra
4.6 (13,145)
Automated Software Testing with Python
Jose Salvatierra, Teclado by Jose Salvatierra
4.5 (3,086)
Python Complete Masterclass for Beginners
Mihai Catalin Teodosiu, EpicPython Academy
4.5 (2,146)

More Python Courses

Python students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.

Request a demo

Courses by Jose Portilla

Learning Python for Data Analysis and Visualization
Jose Portilla
4.3 (15,884)
2021 Complete Python Bootcamp From Zero to Hero in Python
Jose Portilla
4.6 (351,059)
The Complete SQL Bootcamp 2021: Go from Zero to Hero
Jose Portilla
4.7 (93,366)
Spark and Python for Big Data with PySpark
Jose Portilla
4.5 (13,924)
Python 3 : Formation complète à la programmation
Jose Portilla, Marc Augier Programmation Web | Python | Bases de Données, Pierian Data International by Jose Portilla
4.4 (510)
Deep Learning with Python and Keras
Data Weekends, Jose Portilla, Francesco Mosconi
4.5 (2,724)
Python for Financial Analysis and Algorithmic Trading
Jose Portilla
4.5 (15,016)

Courses by Jose Portilla