
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Advanced Concepts
- Python - Abstract Base Classes
- Python - Custom Exceptions
- Python - Higher Order Functions
- Python - Object Internals
- Python - Memory Management
- Python - Metaclasses
- Python - Metaprogramming with Metaclasses
- Python - Mocking and Stubbing
- Python - Monkey Patching
- Python - Signal Handling
- Python - Type Hints
- Python - Automation Tutorial
- Python - Humanize Package
- Python - Context Managers
- Python - Coroutines
- Python - Descriptors
- Python - Diagnosing and Fixing Memory Leaks
- Python - Immutable Data Structures
- Python Useful Resources
- Python - Questions & Answers
- Python - Interview Questions & Answers
- Python - Online Quiz
- Python - Quick Guide
- Python - Reference
- Python - Cheatsheet
- Python - Projects
- Python - Useful Resources
- Python - Discussion
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
Python Interview Questions and Answers
Dear readers, these Python Programming Language Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Python Programming Language. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −
Python Basics Interview Questions
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.
Following are some of the salient features of python −
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building large applications.
It provides very high-level dynamic data types and supports dynamic type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Yes, Python is a case-sensitive language. Which means identifiers, function names, and keywords that has to be distinguished based on the capitalization. Case-sensitivity also helps to maintain the clarity and precision in the code.
Yes, Python is platform-independent. In Python code runs in any operating system with a compatible interpreter. Python codes are executed by the interpreter that abstracts the hardware and Operating system in detail.
Following are the applications of Python −
- Web Development: Frameworks like Django and Flask.
- Data Analysis: Libraries like Pandas and NumPy.
- Machine Learning: Tools such as TensorFlow and Scikitlearn.
- Automation:Scripting and task automation.
- Software Development: Building desktop applications.
Table below explains the difference between Python version 2 and Python version 3.
S.No | Section | Python Version2 | Python Version3 |
---|---|---|---|
1. | Print Function | Print command can be used without parentheses. |
Python 3 needs parentheses to print any string. It will raise error without parentheses. |
2. | Unicode | ASCII str() types and separate Unicode() but there is no byte type code in Python 2. |
Unicode (utf-8) and it has two byte classes −
|
3. | Exceptions | Python 2 accepts both new and old notations of syntax. |
Python 3 raises a SyntaxError in turn when we don't enclose the exception argument in parentheses. |
4. | Comparing Unorderable | It does not raise any error. |
It raises TypeError' as warning if we try to compare unorderable types. |
No, Python doesn't have a double datatype. Python uses float type for floating-point numbers, that determines the double precision default.
Yes, strings in Python are immutable.
No, True cannot be equal to False in Python. In Python True and False are different boolean values.
Python Environment Variables Interview Questions
PYTHONPATH - It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.
PYTHONSTARTUP - It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH.
PYTHONCASEOK − It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.
PYTHONHOME − It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.
Python Data Types and Operations Interview Questions
Python has five standard data types −
Numbers
String
List
Tuple
Dictionary
Assigning Hello world to string.
str = 'Hello World!" print(str)
Output
Hello World!
Here, indexing starts from 0 in Python.
str = 'Hello World!" print(str[0])
Output
H
str = 'Hello World!' print(str[2:5])
Output
llo
str = 'Hello World!' print(str[2:])
Output
llo World!
str = 'Hello World!' print(str * 2)
Output
Hello World!Hello World!
str = 'Hello World!' print(str + TEST)
Output
Hello World!TEST
list = ['abcd', 786 , 2.23, 'john', 70.2 ] print(list)
Output
['abcd', 786 , 2.23, 'john', 70.2 ]
list = ['abcd', 786 , 2.23, 'john', 70.2 ] print(list[0])
Output
abcd
list = ['abcd', 786 , 2.23, 'john', 70.2 ] print(list[1:3])
Output
[786, 2.23]
list = ['abcd', 786 , 2.23, 'john', 70.2 ] print(list[2:])
Output
[2.23, 'john', 70.2]
tinylist = [123, 'john'] print(tinylist * 2)
Output
[123, 'john', 123, 'john']
list1 = [ 'abcd', 786 , 2.23, 'john', 70.2 ] list2 = [123, 'john'] print(list1 + list2)
Output
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Python Tuples Interview Questions
In Python, tuples are immutable sequence used to store multiple items. They cannot be modified after creation and are defined using parameters. Tuples are suitable for fixed collection of items.
The main differences between lists and tuples are − Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) print(tuple)
Output
( 'abcd', 786 , 2.23, 'john', 70.2 )
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) print(tuple[0])
Output
abcd
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) print(tuple[1:3])
Output
(786, 2.23)
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) print(tuple[2:])
Output
(2.23, 'john', 70.2)
tinytuple = (123, 'john') print(tinytuple *2)
Output
(123, 'john', 123, 'john')
tuple = ('abcd', 786 , 2.23, 'john', 70.2 ) tinytuple = (123, 'john') print(tuple + tinytuple)
Output
('abcd', 786 , 2.23, 'john', 70.2, 123, 'john')
Python Dictionaries Interview Questions
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
dict = {} dict['one'] = "This is one" dict[2] = "This is two" tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
Using dictionary.keys() function, we can get all the keys from the dictionary object.
print dict.keys() # Prints all the keys
Using dictionary.values() function, we can get all the values from the dictionary object.
print dict.values() # Prints all the values
Python Strings Interview Questions
To convert a string into an integer in Python, we use 'int()' function. The string represents a valid integer, otherwise, it throws a ValueError.
float()− converts the string to a float where the string must be a numeric value.
str(x)− converts an object to a string
repr(x)− Converts object x to an expression string.
eval(str)− Evaluates a string and returns an object.
tuple(str)−converts a string to a tuple.
tuple('Hello')
Output
('H', 'e', 'l', 'l', 'o')
list(str)− converts a string to a list.
print(list(Hello))
Output
['H', 'e', 'l', 'l', 'o']
set(str)−converts a string to set and if there are any duplicated elements it will be removed.
print(set(Hello))
Output
{'e', 'o', 'H', 'l'}
dict(zip(tup1,tup2))−converts the tuples into a dictionary. zip() function is used to pair the tuples and dict() converters it into the dictionary.
tup1 = ('a', 'b', 'c', 'd') tup2 = (1, 2, 3, 4) dic =dict(zip(tup1,tup2)) print(dic)
Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
capitalize()−This method is used to convert the first character of a string to capital.
str1 = "tutorialspoint" print(str1.capitalize())
Output
Tutorialspoint
isalnum()− Returns true if the string has at least 1 character and all characters are alphanumeric and false otherwise.
isdigit()− Returns true if the string contains only digits and false otherwise.
islower() − Returns true if the string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
isnumeric()−Returns true if a Unicode string contains only numeric characters and false otherwise.
isspace()−Returns true if the string contains only whitespace characters and false otherwise.
istitle()−Returns true if the string is properly "titlecased" and false otherwise.
isupper()− Returns true if the string has at least one cased character and all cased characters are in uppercase and false otherwise.
join(seq)−Merges (concatenates) the string representations of elements in sequence seq into a string, with a separator string.
len(string)−Returns the length of the string.
(width[, fillchar])− Returns a space-padded string with the original string left-justified to a total of width columns.
lower()− Converts all uppercase letters in a string to lowercase.
lstrip()−Removes all leading whitespace in string.
max(str)−Returns the max alphabetical character from the string str.
min(str)− Returns the min alphabetical character from the string str.
replace(): This method will replace every instance of the old substring with the new substring throughout the entire string.
str1 = "Welcome to tutorialspoint " new_str =str1.replace("Welcome",'Hello Welcome') print(new_str)
Output
Hello Welcome to tutorialspoint
strip()− This method returns a new string with all leading (spaces at the beginning) and trailing (spaces at the end) whitespace removed.
str1 = " Welcome to tutorialspoint " Str = str1.strip() print(Str)
Output
Welcome to tutorialspoint
- upper():To convert all the letters of a string to Uppercase.
- lower(): To convert all the letters of a string to Lowercase.
- swap():Used to swap the case of all the letters in a string. If a letter is a small case, then it will change to capital letters and vice versa.
- capitalize():used to capitalize the first letter of the string
- title():Used to capitalize the first letter of each word of the string.
title()− It is used to capitalize the first letter of each word of the string.
upper()−used to convert all the letters of a string to Uppercase.
isdecimal()− Returns true if a Unicode string contains only decimal characters and false otherwise.
Python Lists Interview Questions
The del() and remove() methods both are used to remove an element from a list. The del() is used to delete an element at a specified index value. It can also remove multiple elements using slicing operations. For example, The remove() method of a list is used to remove the first occurrence of an element.
List = [1,2,3,4,5,6] #deleting an element del List[1] #deleting using sliding operation del List[2:3] #removing 5 List.remove(5) print(List)
Output
[1, 3, 6]
The len() function returns the length of the list.(Output:3)
[1, 2, 3, 4, 5, 6]
['Hi!', 'Hi!', 'Hi!', 'Hi!']
True
1 2 3
3
2
3
To compare two lists, we need to use equality[ ==]. If both lists contain the same values, it will return True; otherwise, it will return False.
list1=[1,2,3,4] list2=[1,2,3,4] print(list1==list2)
Output
True
Using the len() function we can find the length of the list.
list1 = [1,2,3,4,5] print(len(list1))
Output
5
Using the max() function we can find the maximum element of the list.
list1 = [10, 20, 30, 40, 50] print(max(list1))
Output
50
Using the min() function we can find the minimum element of the list.
list1 = [10, 20, 30, 40, 50] print(min(list1))
Output
10
Using the index() function we can get the index value of an element.
list1 = [10, 20, 30, 40, 50] print(list1.index(30))
Output
2
insert() function is used to insert an element at a particular index. It accepts index-value and object as parameters.
list1 = ['a', 'b', 'c', 'd','e'] list1.insert(3,'z')
Output
['a', 'b', 'c', 'z', 'd', 'e']
pop() function is used to remove the last object from a list. We can also pass the index value as an argument and it returns the object at that specific index.
list1 = ['a', 'b', 'c', 'd','e'] list1.pop() list1.pop(2) print(list1)
Output
['a', 'b', 'd']
Using remove(), del(), and pop() we can remove an element from a list.
list1 = ['a', 'b', 'c', 'd','e'] list1.pop() list1.pop(2) print(list1)
Output
['a', 'b', 'd']
reverse() function is used to reverse a list. Using list slicing[::-1] we can also reverse the list.
list1 = ['a', 'b', 'c', 'd','e'] print(list1.reverse()) list2 = [1,2,3,4,5] rev=list2[::-1] print(rev)
Output
['e', 'd', 'c', 'b', 'a'] [5, 4, 3, 2, 1]
Using sort() function is used to arrange the elements of the list in a specific order. By default, it arranges the elements in ascending order. To arrange the elements in descending order we can reverse the sorted list using the reverse() function.
list1 = [13,10,45,9,5,12] list1.sort() print(list1)
Output
[5, 9, 10, 12, 13, 45]
Python Operators Interview Questions
The ** operator is used to perform exponential operations where a number is used to raise the power of another number. For example, 2**3 means 2 is raised to the power of 3.
// operator is used to perform floor division. It divides two numbers and returns the largest integer value less than or equal to the result of the division.
print(9//5)
Output
1
The is operator in Python is used to check if two variables refer to the same object in memory. It compares the identity of the objects, not their values.
The not in operator in Python is used to check if a specific element is not present in a sequence, such as a list, tuple, string, or dictionary. If the element is not found, the operator returns True; otherwise, it returns False.
Python Control Statements Interview Questions
The break statement is used to terminate the execution of a loop when a particular condition is met. Once the break statement is executed, the loop stops immediately, and the program continues with the next statement following the loop.
The continue statement in Python is used to skip the rest of the code inside a loop for the current iteration and move directly to the next iteration of the loop. Unlike the break statement, which terminates the loop entirely, continue only skips to the next iteration without ending the loop.
The Python pass is a null statement, which can be replaced with future code. It is used when we want to implement the function or conditional statements in the future, which has not been implemented yet. When we define a loop or function if we leave the block empty we will get an IndentationError so, to avoid this error we use pass.
Python Random Module Interview Questions
To pick a random item from a list or tuple in Python, we use the random.choice() function. This function returns a random selected element from the given list and tuple . This ensures us to import the random module by adding import random. This method id useful for selecting random samples, shuffling items, and creating simple games that require randomization.
To pick a random item from a range in Python, we use random.choice() function. It returns a randomly selected element from the range 'start' to 'stop - 1'. This will also select the random number from the specified range.
random() − returns a random float r, such that 0 is less than or equal to r and r is less than 1.
seed([x]) − Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None.
shuffle(lst) − Randomizes the items of a list in place. Returns None.
Python Functions and Memory Interview Questions
lambda' is a keyword in python which creates an anonymous function. Lambda does not contain block of statements. It does not contain return statements.
An incomplete version of a function is often called stub or partial function. These are typically a placeholder functions that may not have implementations or used during development for testing other parts of a code.
The memory area where parameters and local variables are stored in a function is defined as stack. Here, stack manages the function calls, stores the variables and returns the address of a particular file.
Python Modules and Libraries Interview Questions
The OS module in Python is used to interact with the operating system. It provides file and directory manipulation, process management, environment variables, enables Python scripts to perform OS related tasks from different platforms.
The 'scikit-learn' library in Python is used for machine learning.
Python uses several tools to find buys, they are −
- pdb: The built - in Python debugger for interactive debugging.
- pylint: Static code analysis tool that checks for errors.
- pyflakes:Without executing the code it analyzes it.