22
DecMastering Python Viva Interview Questions You Need to Know
Python Viva Questions and Answers
Python Vivatypically assesses a candidate’s knowledge of Python programming, problem-solving skills, and understanding of core concepts such as data structures, algorithms, and object-oriented programming. Python Viva Questions often focus on practical coding challenges, language-specific features, and best practices. By preparing for common Python Viva Questions and Answers, candidates can better demonstrate their ability to write efficient code and solve complex problems in real-world scenarios.
In this Interview Tutorial, you will get to understand the Top Python Interview Questions and Answers, including Python Viva Questions and Answers for the Advanced Level, Python Viva Questions and Answers for NumPy, Python Libraries Viva Questions and Answers, and a lot more asked in any interview.
Top 20 Python Viva Questions and Answers for Basic Level
Q 1. What is Python?
Python is a high-level, interpreted, and general-purpose programming language. It is known for its easy-to-read syntax and versatility, making it suitable for various applications, including web development, data analysis, and artificial intelligence.
Q 2. What are the key features of Python?
Some key features of Python include:
- Easy syntax and readability
- Interpreted and dynamically typed
- Supports object-oriented, functional, and procedural programming
- Large standard library
- Cross-platform compatibility
Q 3. What is PEP 8?
PEP 8 is the Python Enhancement Proposal that provides guidelines for writing clean and readable Python code. It covers naming conventions, indentation styles, and other coding standards to ensure consistency and maintainability.
Q 4. What are Python's data types?
There are several built-in data types in Python, including:
- Numeric types: int, float, complex
- Sequence types: list, tuple, range
- Mapping type: dict
- Set types: set, frozenset
- Text type: str
- Boolean type: bool
- Binary types: bytes, bytearray, memoryview
Q5. What are lists and tuples in Python?
List in Python: Lists are mutable (modifiable) ordered collections in Python that can hold a variety of object types, including integers, strings, and other lists. They allow for dynamic resizing.
Example
my_list = [1, 2, 3, "hello"] # A list with mixed data types
my_list.append(4) # Adds an element
print(my_list)
Output
[1, 2, 3, 'hello', 4]
Tuples in Python: Tuples are immutable (non-modifiable) ordered collections in Python. Once created, the elements in a tuple cannot be changed, making them suitable for storing fixed data.
Example
my_tuple = (1, 2, 3, "world") # A tuple with mixed data types
# my_tuple[1] = 5 # Error: Tuples do not support item assignment
print(my_tuple)
Output
(1, 2, 3, 'world')
Q 6. What is a dictionary in Python?
A dictionary in Python is a collection of key-value pairs where each key is unique. It is unordered, mutable, and indexed. It allows fast lookups and is defined using curly braces { }.
Example
# Creating a dictionary
person = {
"name": "Aman",
"age": 25,
"city": "New York"
}
# Accessing dictionary elements
print("Name:", person["name"])
print("Age:", person["age"])
print("City:", person["city"])
# Adding a new key-value pair
person["job"] = "Software Developer"
print("Updated dictionary:", person)
# Modifying an existing value
person["age"] = 26
print("Updated age:", person["age"])
# Removing a key-value pair
del person["city"]
print("After removal:", person)
# Looping through dictionary keys and values
for key, value in person.items():
print(f"{key}: {value}")
# Checking if a key exists
if "name" in person:
print("Name exists in the dictionary.")
# Getting all keys and values
keys = person.keys()
values = person.values()
print("Keys:", keys)
print("Values:", values)
# Merging dictionaries
additional_info = {"hobbies": ["Reading", "Traveling"], "age": 27}
person.update(additional_info)
print("Merged dictionary:", person)
Output
Name: Aman
Age: 25
City: New York
Updated dictionary: {'name': 'Aman', 'age': 25, 'city': 'New York', 'job': 'Software Developer'}
Updated age: 26
After removal: {'name': 'Aman', 'age': 26, 'job': 'Software Developer'}
name: Aman
age: 26
job: Software Developer
Name exists in the dictionary.
Keys: dict_keys(['name', 'age', 'job'])
Values: dict_values(['Aman', 26, 'Software Developer'])
Merged dictionary: {'name': 'Aman', 'age': 27, 'job': 'Software Developer', 'hobbies': ['Reading', 'Traveling']}
Q 7. What is the difference between deepcopy() and shallow copy()?
The main difference between deepcopy() and shallow copy() are:
- A shallow copy creates a new object but inserts references to the original objects' elements.
- A deep copy creates a new object and recursively copies all objects found in the original object, ensuring no references to the original objects are retained.
Q 8. What is a function in Python?
A function in Python is a block of reusable code that performs a specific task. It is defined using the def keyword, and parameters can be passed to the function for execution.
Q 9. What is the difference between range() and xrange() in Python?
The difference between range() and xrange() in Python:Fvar
- range() in Python 2 returns a list, and xrange() returns an iterator, which is more memory efficient.
- In Python 3, range() behaves like xrange() in Python 2 and returns an iterator.
Q 10. What are Lambda functions?
A lambda function in Python is a small anonymous function defined using the lambda keyword. It can take any number of arguments but only has one expression.
Example
# A lambda function to find the square of a number
square = lambda x: x ** 2
print("Square of 5:", square(5))
Output
Square of 5: 25
Q 11. What is an iterator in Python?
An iterator is an object that allows traversing through all the elements of a collection, such as a list or tuple. It implements two methods: __iter__() and __next__().
Q 12. What is the difference between is and == in Python?
The difference between is and == in Python
- == checks if the values of two objects are equal.
- is checks if two objects refer to the same memory location (i.e., they are the same object).
Q 13. What are decorators in Python?
A decorator is a function that modifies the behavior of another function. It is used to add functionality to existing code in a reusable manner.
Q 14. What is the purpose of self in Python?
self represents the instance of the class in object-oriented programming. It is used to access variables and methods within the class and distinguish between instance variables and local variables.
Q 15. What are Python modules and packages?
- A module is a file containing Python code, and it can define functions, classes, and variables.
- A package is a collection of modules organized in directories, which allows for a hierarchical structure.
Q 16. What is a class in Python?
A class in Python is a blueprint for creating objects (instances). It defines the methods and attributes that the objects created from it will have.
Q 17. What are exception-handling mechanisms in Python?
Python uses try, except, else, and finally blocks to handle exceptions. The code inside try is executed, and if an error occurs, it is handled in the except block. The else block executes if no exception occurs, and finally executes regardless of an exception.
Q 18. What is the difference between append() and extend() in Python?
The difference between append() and extend() in Python:
- append() adds a single element to the end of a list.
- extend() adds all elements from an iterable to the end of the list.
Q 19. What is the use of the with statement in Python?
The with statement is used for resource management, such as file handling. It automatically takes care of setup and cleanup actions, like closing a file after opening it.
Q20. What are list comprehensions in Python?
List comprehensions in Python provide a concise way to create lists. They consist of an expression followed by a for clause, optionally including if conditions.
Example
# List of numbers
numbers = [1, 2, 3, 4, 5]
# List comprehension to square each number
squared_numbers = [x ** 2 for x in numbers]
print("Squared Numbers:", squared_numbers)
Output
Squared Numbers: [1, 4, 9, 16, 25]
Top 20 Python Viva Questions and Answers for Advanced Level
Q 21. What is the difference between Python 2 and Python 3?
Python 2 and Python 3 have several differences. Some key differences include:
- Python 3 uses print() as a function, while Python 2 uses it as a statement.
- Integer division in Python 2 rounds down by default, while Python 3 uses true division (decimal results).
- In Python 3, Unicode strings are the default, while in Python 2, strings are ASCII unless explicitly declared as Unicode.
Q 22. How does Python handle memory management?
Python uses automatic memory management, which includes a garbage collection system that cleans up unused objects. The memory is managed through reference counting and cyclic garbage collection. The gc module isused for Python garbage collection.
Q 23. Explain Python's Global Interpreter Lock (GIL).
The Global Interpreter Lock (GIL) is a mutex that protects access to Python objects, ensuring that only one thread can execute Python bytecode at a time. This can be a bottleneck in CPU-bound multi-threaded programs but does not affect I/O-bound tasks.
Q 24. What is the difference between a method and a function in Python?
The difference between a method and a function in Python:
- A function is a block of code that is defined using the def keyword and can be called independently of classes.
- A method is a function that is associated with an object and is called on the object itself. Methods are typically defined inside a class.
Q 25. What are Python decorators, and how do they work?
A decorator is a function that takes another function as an argument and extends or alters its behavior without modifying the function itself. Decorators are commonly used for logging, access control, caching, and other repetitive tasks.
Q 26. What are Python generators, and how do they differ from iterators?
- Generators are a type of iterable in Python that allows lazy evaluation. They are defined using the yield keyword and are more memory efficient than normal functions.
- Iterators are objects that implement the __iter__() and __next__() methods. Generators are a simpler and more memory-efficient form of iterators.
Q 27. What is the difference between @staticmethod and @classmethod?
- @staticmethod is used to define a method that does not require access to the instance (self) or the class (cls), meaning it works like a regular function but belongs to the class.
- @classmethod is used to define a method that takes the class as its first argument (cls), allowing it to modify the class state.
Q 28. How can you handle multiple exceptions in Python?
Multiple exceptions can be handled using a single except block by specifying them in a tuple. For example:
try:
# some code
except (TypeError, ValueError) as e:
print(f"Error: {e}")
Q 29. What are Python’s built-in data structures?
Python has several built-in data structures:
- Lists (ordered, mutable)
- Tuples (ordered, immutable)
- Dictionaries (unordered, mutable key-value pairs)
- Sets (unordered, mutable, no duplicates)
- Frozensets (immutable sets)
- Queues(FIFO, implemented using collections.deque)
Q 30. Explain the with statement in Python.
The with statement is used for resource management (e.g., file handling). It simplifies exception handling and ensures that resources like files or network connections are automatically closed after use. It is used with objects that implement the context management protocol (__enter__ and __exit__ methods).
Q 31. What is the difference between del and remove() in Python?
- del is a keyword used to delete an object, list item, or variable from memory.
- remove() is a method used on lists to remove the first occurrence of a specified value from the list.
Q 32. What are Python’s built-in modules?
Python provides a rich set of built-in modules, such as:
- os for interacting with the operating system
- sys for interacting with the Python runtime environment
- math for mathematical operations
- datetime for working with dates and times
- json for handling JSON data
- collections for specialized data structures like deque, Counter, etc.
Q 33. What is the difference between __str__() and __repr__() in Python?
- __str__() is used to define a user-friendly string representation of an object. It is used by the print() function.
- __repr__() is used to define a string representation that is unambiguous and can be used to recreate the object. It is often used for debugging.
Q 34. What is the finally block in exception handling?
The finally block is executed no matter what, whether an exception occurs or not. It is typically used for cleanup operations, such as closing files or releasing resources.
Q 35. What is the purpose of the super() function in Python?
The super() function is used to call methods from a parent class in a subclass, allowing for method overriding and inheritance chains. It is often used to extend or modify the behavior of inherited methods.
Q 36. What is the isinstance() function used for?
The isinstance() function is used to check if an object is an instance or subclass of a particular class. Example:
isinstance(obj, ClassName)
Q 37. What are list comprehensions, and how do they work in Python?
A list comprehension is a compact way to process and filter elements in a list. It allows for writing more concise and readable code. For example:
squares = [x**2 for x in range(10) if x % 2 == 0]
Q 38. How do you perform unit testing in Python?
Unit testing in Python is commonly done using the built-in unittest module.
Steps to perform unit testing in Python:
- Import the unittest module.
- Create a test class that inherits from unittest.TestCase.
- Define test methods inside the class. Each test method must start with test_.
- Use assertion methods such as assertEqual(), assertTrue(), assertRaises(), etc., to check the expected outcomes.
- Run the tests by calling unittest.main() or using a test runner.
Q 39. What are the differences between staticmethod and class method in Python?
- staticmethod does not take any special first argument (self or cls). It behaves like a regular function but is scoped within the class.
- classmethod takes the class itself (cls) as its first argument and can modify the class state, while a static method cannot.
Q 40. Explain the concept of "duck typing" in Python.
Duck typing refers to the idea that an object's suitability for use is determined by its behavior (methods and attributes) rather than its class or type. If an object behaves like a certain type (e.g., it has a walk() method), it can be treated as that type, even if it isn't an explicit subclass of the expected type.
Top 15 Python Viva Questions and Answers for Object-Oriented Programming
Q 41. What is Object-Oriented Programming (OOP)?
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects," which can contain data in the form of fields (attributes) and code in the form of procedures (methods). The four main principles of OOP are:
- Encapsulation: Bundling data and methods that operate on that data within a single unit, called a class.
- Abstraction: Hiding the complexity and only exposing the necessary parts of the object.
- Inheritance: Creating a new class from an existing class by inheriting its attributes and methods.
- Polymorphism: Allowing different classes to be treated as instances of the same class through inheritance, but each class can implement its own version of methods.
Q 42. What are classes and objects in Python?
- A class is a blueprint or template for creating objects. It defines the attributes and behaviors that the objects created from the class will have.
- An object is an instance of a class. It is a specific realization of the class with its own state (data) and behavior (methods).
Q 43. What is inheritance in Python?
Inheritance In Python allows a class to inherit attributes and methods from another class. The new class (called the child or subclass) inherits the properties and methods of the existing class (called the parent or superclass) and can override or extend them. Inheritance promotes code reuse.
Example
# Base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
# Derived class
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
# Using the classes
animal = Animal("Generic Animal")
dog = Dog("Buddy")
print(animal.speak())
print(dog.speak())
Output
Generic Animal makes a sound.
Buddy says Woof!
Q 44. What is the difference between __init__ and __new__ in Python?
- __init__ is the constructor method that is called after an object is created. It is used to initialize the object's state.
- __new__ is a method that is responsible for creating the object in memory. It is called before __init__.
Q 45. What is polymorphism in Python?
Polymorphism allows different classes to implement the same method or behavior differently. In Python, polymorphism can be achieved through method overriding (in inheritance) or method overloading (using default arguments).
Example
# Base class
class Animal:
def speak(self):
return "Animal makes a sound."
# Derived class 1
class Dog(Animal):
def speak(self):
return "Dog says Woof!"
# Derived class 2
class Cat(Animal):
def speak(self):
return "Cat says Meow!"
# Function demonstrating polymorphism
def animal_sound(animal):
return animal.speak()
# Creating objects
dog = Dog()
cat = Cat()
# Using polymorphism
print(animal_sound(dog))
print(animal_sound(cat))
Output
Dog says Woof!
Cat says Meow!
Q 46. What is encapsulation in Python?
Encapsulation is the concept of restricting direct access to some of an object's attributes and methods. It helps to protect the object's internal state by exposing only the necessary parts. In Python, this is typically done by defining private variables (prefixing with _
or __
) and providing getter and setter methods.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner # Public attribute
self.__balance = balance # Private attribute (encapsulated)
# Getter method for balance
def get_balance(self):
return self.__balance
# Setter method for balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
else:
print("Deposit amount must be positive.")
# Method to withdraw money
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
else:
print("Invalid withdrawal amount.")
# Creating a BankAccount object
account = BankAccount("Alice", 1000)
# Accessing public and private attributes
print("Account owner:", account.owner) # Accessible
print("Initial balance:", account.get_balance()) # Access private attribute via method
# Modifying the balance using encapsulated methods
account.deposit(500)
account.withdraw(200)
print("Updated balance:", account.get_balance()) # Access updated balance
Output
Account owner: Alice
Initial balance: 1000
Updated balance: 1300
Q 47. What is an abstract class in Python?
An abstract class in Python is a class that cannot be instantiated on its own and must be subclassed. It can contain abstract methods, which are methods without implementation that must be overridden by subclasses.
Q 48. What is the difference between @staticmethod and @classmethod?
- @staticmethod defines a method that does not take any special first argument (e.g., self or cls). It is used when a method does not need to modify the object's state or class state.
- @classmethod defines a method that takes the class as its first argument (cls). It is used when a method needs to modify the class state or access class-level properties.
Q 49. What is the purpose of the super() function in Python?
The super() function is used to call methods from a parent class in a subclass, allowing for method overriding and inheritance chains. It is commonly used in the __init__ method to initialize parent class attributes.
Q 50. What are __str__() and __repr__() methods in Python?
- __str__() is used to define the user-friendly string representation of an object. It is called by the print() function.
- __repr__() is used to define the official string representation of an object that is unambiguous and can be used to recreate the object. It is often used for debugging.
Q 51. What is method overloading in Python?
Python does not support method overloading in the traditional sense (i.e., defining multiple methods with the same name but different signatures). However, method overloading can be simulated by using default arguments or variable-length arguments (*args, **kwargs).
Example
class Calculator:
def add(self, a, b=None):
if b is None:
return a + a # Overloading to handle one argument (returns double)
else:
return a + b # Normal addition for two arguments
# Creating a Calculator object
calc = Calculator()
# Calling the add method with one and two arguments
print(calc.add(5))
print(calc.add(5, 3))
Output
10
8
Q 52. What is multiple inheritance in Python?
Multiple inheritance is when a class inherits from more than one parent class. Python supports multiple inheritance, but it can lead to complex situations such as the "diamond problem." It is handled using the Method Resolution Order (MRO) in Python.
Example
# Base class 1
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
# Base class 2
class Mammal:
def __init__(self, is_warm_blooded=True):
self.is_warm_blooded = is_warm_blooded
def is_warm_blooded(self):
return self.is_warm_blooded
# Derived class (Multiple inheritance)
class Dog(Animal, Mammal):
def __init__(self, name):
Animal.__init__(self, name)
Mammal.__init__(self)
def speak(self):
return f"{self.name} says Woof!"
# Creating a Dog object
dog = Dog("Buddy")
print(dog.speak())
print(dog.is_warm_blooded)
Output
Buddy says Woof!
True
Q 53. What is the difference between self and cls in Python?
The difference between self and cls in Python
- self is used in instance methods to refer to the instance of the class (i.e., the object itself).
- cls is used in class methods to refer to the class itself (i.e., the class that the method is called on).
Q 54. What is the __del__ method in Python?
The __del__() method is the destructor in Python, which is called when an object is about to be destroyed. It is used to clean up resources (e.g., closing files or network connections). However, it is not guaranteed to be called immediately when an object goes out of scope due to Python's garbage collection mechanism.
Example
class MyClass:
def __init__(self, name):
self.name = name
print(f"Object {self.name} created.")
def __del__(self):
print(f"Object {self.name} is being destroyed.")
# Creating an object
obj = MyClass("Test Object")
# Deleting the object explicitly (or it will be automatically deleted when it goes out of scope)
del obj
Output
Object Test Object created.
Object Test Object is being destroyed.
Q 55. Can Python classes have private members?
Python does not have strict access control like other languages (e.g., Java). However, it does provide a convention for private members by prefixing them with a single underscore (_
) or double underscore (__
). While the members are not truly private, this serves as a guideline for internal use.
class MyClass:
def __init__(self):
self._internal_var = 42
self.__private_var = 24
Top 15 Python Viva Questions and Answers for Pandas
Q 56. What is Pandas in Python?
Pandas is an open-source Python library used for data manipulation and analysis. It provides data structures like DataFrame
and Series
that are efficient for handling large datasets and performing operations like grouping, merging, reshaping, and cleaning data.
Q 57. What is the difference between a Pandas DataFrame and a Pandas Series?
The difference between a Pandas DataFrame and a Pandas Series:
- DataFrame: A 2-dimensional labeled data structure with columns of potentially different types. It's like a table or a spreadsheet with rows and columns.
- Series: A 1-dimensional labeled array that can hold any data type. It is essentially a single column in a DataFrame.
Q 58. How do you create a DataFrame in Pandas?
You can create a DataFrame using a dictionary or a listor from external files like CSV or Excel.
import pandas as pd
# From a dictionary
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
Q 59. What is the purpose of the read_csv() function in Pandas?
The read_csv() function is used to read a CSV file and convert it into a DataFrame. It can handle large files and support various customization options like delimiters, handling missing values, and specifying data types.
df = pd.read_csv('data.csv')
Q 60. How do you handle missing data in Pandas?
Pandas provides several methods for handling missing data, such as:
- dropna(): Removes missing values.
- fillna(): Replaces missing values with a specified value or method (e.g., forward fill or mean).
df.dropna() # Drops rows with missing values
df.fillna(0) # Replaces missing values with 0
Q 61. What is the difference between loc[] and iloc[] in Pandas?
The difference between loc[] and iloc[] in Pandas
- loc[]: Accesses data by label (i.e., row/column names).
- iloc[]: Accesses data by index (i.e., integer position).
df.loc[1, 'Age'] # Accesses row with label 1 and column 'Age'
df.iloc[1, 2] # Accesses row with index 1 and column at index 2
Q 62. What is the groupby() function in Pandas?
The groupby() function is used to split the data into groups based on some criteria and perform aggregate operations like sum, mean, or count. It is commonly used for data aggregation and summarization.
df.groupby('Age').mean() # Groups by 'Age' and computes the mean of other columns
Q 63. How can you filter data in a Pandas DataFrame?
You can filter data using conditions inside square brackets or using the query() method.
df[df['Age'] > 30] # Filters rows where Age is greater than 30
df.query('Age > 30') # Using query method
Q 64. What is the pivot_table() function in Pandas?
The pivot_table() function is used to create a pivot table by summarizing data based on some column(s) and applying aggregation functions like sum or mean.
df.pivot_table(values='Age', index='Name', aggfunc='mean')
Q 65. What are some ways to sort data in a DataFrame?
You can sort data in Pandas using the sort_values() function by specifying the column(s) to sort by.
df.sort_values(by='Age') # Sorts by the 'Age' column
df.sort_values(by='Age', ascending=False) # Sorts in descending order
Q 66. How do you concatenate two or more DataFrames in Pandas?
You can use the concat() function to concatenate DataFrames along a particular axis (rows or columns).
df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df2 = pd.DataFrame({'A': [5, 6], 'B': [7, 8]})
df_combined = pd.concat([df1, df2], axis=0) # Concatenate along rows
Q 67. What is the purpose of the apply() functionin Pandas?
The apply() function allows you to apply a function along the axis (rows or columns) of a DataFrame. It can be used for element-wise operations or to apply a custom function to data.
df['Age'] = df['Age'].apply(lambda x: x + 1) # Adds 1 to each Age
Q 68. How can you merge two DataFrames in Pandas?
You can merge DataFrames using the merge() function, similar to SQL joins (inner, left, right, outer).
df1 = pd.DataFrame({'ID': [1, 2], 'Name': ['Alice', 'Bob']})
df2 = pd.DataFrame({'ID': [1, 3], 'Age': [25, 30]})
df_merged = pd.merge(df1, df2, on='ID', how='inner') # Inner join on 'ID'
Q 69. How do you get summary statistics for a DataFrame?
You can use the describe() function to get summary statistics such as mean, standard deviation, min, and max for numerical columns.
df.describe()
Q 70. How do you handle duplicates in a DataFrame?
Pandas provides the drop_duplicates() function to remove duplicate rows from a DataFrame.
df.drop_duplicates() # Removes duplicate rows
Top 15 Python Viva Questions and Answers for NumPy
Q 71. What is NumPy in Python?
NumPy is an open-source Python library for numerical computing. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays efficiently.
Q 72. How do you create a NumPy array?
You can create a NumPy array using the np.array() function, which can convert Python lists or tuples into arrays.
import numpy as np
arr = np.array([1, 2, 3])
Q 73. What is the difference between a Python list and a NumPy array?
The difference between a Python list and a NumPy array:
- Python list: Can hold elements of different data types.
- NumPy array: Holds elements of the same data type, making it more efficient for numerical computations. Supports element-wise operations and is optimized for performance.
Q 74. What are the benefits of using NumPy arrays over Python lists?
NumPy arrays offer better performance for numerical operations, as they are implemented in C and optimized for fast operations. They are more memory-efficient, support vectorized operations, and allow for advanced indexing and slicing.
Q 75. What is the shape of a NumPy array?
The shape of a NumPy array is a tuple that represents the number of elements in each dimension. For example, a 2D array with 3 rows and 4 columns will have a shape of (3, 4).
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) # Output: (2, 3)
Q 76. How do you reshape a NumPy array?
You can reshape a NumPy array using the reshape() function. This allows you to change the dimensions of the array without changing its data.
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped_arr = arr.reshape(2, 3) # Reshapes to 2 rows, 3 columns
Q 77. What is broadcasting in NumPy?
Broadcasting is a set of rules that NumPy follows to perform element-wise operations on arrays of different shapes. It automatically expands the smaller array to match the shape of the larger array during the operation.
arr1 = np.array([1, 2, 3])
arr2 = np.array([1])
result = arr1 + arr2 # arr2 is broadcasted to match the shape of arr1
Q 78. What are some common ways to initialize a NumPy array?
You can initialize a NumPy array using the following functions:
- np.zeros(): Creates an array of zeros.
- np.ones(): Creates an array of ones.
- np.arange(): Creates an array with evenly spaced values.
- np.linspace(): Creates an array with a specified number of evenly spaced values.
np.zeros((2, 3)) # 2x3 array of zeros
np.ones((2, 3)) # 2x3 array of ones
np.arange(0, 10, 2) # Array with values from 0 to 10 with a step of 2
np.linspace(0, 10, 5) # Array with 5 evenly spaced values between 0 and 10
Q 79. How do you perform element-wise operations on NumPy arrays?
NumPy supports element-wise operations, which means you can perform mathematical operations (e.g., addition, subtraction, multiplication, etc.) directly on arrays.
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = arr1 + arr2 # Element-wise addition
Q 80. How do you compute the mean, median, and standard deviation of a NumPy array?
You can compute statistical values like mean, median, and standard deviation using NumPy functions:
arr = np.array([1, 2, 3, 4, 5])
mean = np.mean(arr) # Mean
median = np.median(arr) # Median
std_dev = np.std(arr) # Standard Deviation
Q 81. What is the difference between np.copy() and simple assignment?
np.copy() creates a new array with the same data, whereas simple assignment (e.g., arr2 = arr1) creates a reference to the same array. Changes made to one will affect the other when using simple assignment.
arr1 = np.array([1, 2, 3])
arr2 = arr1.copy() # arr2 is a copy, changes to arr2 won't affect arr1
Q 82. How do you index and slice a NumPy array?
You can index and slice NumPy arrays similarly to Python lists, but NumPy arrays support advanced slicing and multi-dimensional indexing.
arr = np.array([1, 2, 3, 4, 5])
slice_arr = arr[1:4] # Slices elements from index 1 to 3 (not 4)
Q 83. How do you find the maximum and minimum values of a NumPy array?
You can use the np.max() and np.min() functions to find the maximum and minimum values, respectively.
arr = np.array([1, 2, 3, 4, 5])
max_val = np.max(arr) # Maximum value
min_val = np.min(arr) # Minimum value
Q 84. What is the purpose of the np.dot() function?
The np.dot() function is used to compute the dot product of two arrays. It can be used for both matrix multiplication and vector dot product.
arr1 = np.array([1, 2])
arr2 = np.array([3, 4])
result = np.dot(arr1, arr2) # Dot product
Q 85. How do you stack NumPy arrays vertically and horizontally?
You can stack arrays vertically and horizontally using np.vstack() and np.hstack(), respectively.
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
vstack_arr = np.vstack((arr1, arr2)) # Stacks arrays vertically
hstack_arr = np.hstack((arr1, arr2)) # Stacks arrays horizontally
Top 20 Python Libraries Viva Questions and Answers
Q 86. What are Python libraries?
Python libraries are pre-written code or modules that provide functionality to perform various tasks without needing to code everything from scratch. They include functions, classes, and methods to make coding easier.
Q 87. What is the purpose of NumPy?
NumPy is a Python library for numerical computing. It provides support for arrays and matrices, along with a large collection of mathematical functions to operate on these data structures efficiently.
Q 88. What is Pandas used for?
Pandas is a library for data manipulation and analysis. It provides data structures like Series and DataFrame, which are used to handle structured data (e.g., CSV files, Excel files, SQL queries).
Q 89. Explain Matplotlib and its usage.
Matplotlib is a plotting library in Python used to create static, animated, and interactive visualizations. It allows users to plot graphs, charts, and images from data.
Q 90. What is Seaborn in Python?
Seaborn is a Python data visualization library built on top of Matplotlib. It provides a high-level interface for drawing attractive statistical graphics and visualizations, such as heatmaps, box plots, and violin plots.
Q 91. What is the difference between NumPy and Pandas?
- NumPy: Used for numerical computations, supporting large, multi-dimensional arrays and matrices.
- Pandas: A data manipulation library designed for handling structured data with tools like Series and DataFrame, supporting complex operations like groupby, merging, and reshaping.
Q 92. What is the use of the Requests library?
The requests library in Python is used to send HTTP requests and interact with RESTful APIs. It simplifies making HTTP requests, handling responses, and dealing with headers, cookies, and sessions.
Q 93. Explain the role of BeautifulSoup in web scraping.
BeautifulSoup is a Python library used for web scraping purposes. It allows users to parse HTML and XML documents, extract useful information, and navigate through complex web page structures.
Q 94. What is Flask used for?
Flask is a lightweight web framework for Python. It is used to build web applications and APIs. Flask is simple to use and gives developers control over app structure and routing.
Q 95. How does Django differ from Flask?
- Flask: A micro-framework that is lightweight and flexible, allowing you to build custom applications with minimal setup.6Django: A full-stack framework that includes built-in features such as user authentication, ORM, and admin interfaces, providing a more structured approach.
Q 96. What is TensorFlow used for?
TensorFlow is an open-source machine-learning library developed by Google. It is used for building and training deep learning models, such as neural networks, for tasks like image recognition, language processing, and more.
Q 97. What is Keras?
Keras is an open-source deep-learning framework that provides a high-level interface for building and training neural networks. Keras is built on top of TensorFlow and makes it easier to develop deep learning models.
Q 98. What is PyTorch?
PyTorch is an open-source deep-learning library developed by Facebook. It provides dynamic computation graphs and supports GPU acceleration, making it popular for research and production-level applications.
Q 99. What is Scikit-learn used for?
Scikit-learn is a machine-learning library in Python. It provides simple and efficient tools for data mining and data analysis, including algorithms for classification, regression, clustering, and dimensionality reduction.
Q 100. What is OpenCV used for?
OpenCV is a computer vision library used to process and analyze images and videos. It provides various tools for real-time computer vision applications such as object detection, face recognition, and image manipulation.
Q 101. What is Pillow in Python?
Pillow is a Python Imaging Library (PIL) that adds image processing capabilities to Python. It provides functions for opening, manipulating, and saving many different image file formats.
Q 102. What is SQLAlchemy?
SQLAlchemy is a Python SQL toolkit and Object-Relational Mapping (ORM) library. It provides tools for working with relational databases, allowing developers to interact with databases using Python objects and expressions instead of SQL queries.
Q 103. What is SciPy used for?
SciPy is a Python library used for scientific and technical computing. It builds on NumPy and provides additional functionality for optimization, integration, interpolation, eigenvalue problems, and other scientific tasks.
Q 104. What is the purpose of the Plotly library?
Plotly is a graphing library for creating interactive and publication-quality visualizations. It supports a wide range of chart types, including line charts, bar charts, heatmaps, and 3D plots.
Q 105. What is the purpose of the SQLite3 library in Python?
SQLite3 is a Python library used to interact with SQLite databases. It provides a lightweight, serverless, and self-contained database engine for storing and managing relational data.
Conclusion
In conclusion, mastering Python viva questions and answers is crucial for excelling in technical assessments. By practicing these commonly asked queries, you'll build confidence and demonstrate strong problem-solving skills. This guide of Python viva questions and answers serves as a valuable resource to refine your knowledge. Prepare thoroughly, and success will be within your reach!
FAQs
- *args: Used to pass a variable number of positional arguments.
- **kwargs: Used to pass a variable number of keyword arguments.