Imp Question - Python Questions by Hari For Placement

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

IMPORTANT QUESTIONS FOR INTERVIEWS IN C, JAVA & PYTHON

Most asked PYTHON interview questions for freshers:

1 What is a List
In Python, a list is a built-in data structure that represents an ordered collection
of elements. It is one of the most commonly used data structures in Python due
to its flexibility and versatility. Lists can contain elements of different data types,
and you can add, remove, modify, and access elements in a list.
List elements are enclosed in square brackets [], and each element is separated by a comma. Lists are
mutable, meaning you can change their contents after creation.
Here's an example of creating a list in Python:
# Creating a list
fruits = ['apple', 'banana', 'orange', 'grape', 'mango']

# Accessing elements in the list using index


print(fruits[0]) # Output: apple
print(fruits[2]) # Output: orange

# Modifying elements in the list


fruits[1] = 'pear'
print(fruits) # Output: ['apple', 'pear', 'orange', 'grape',
'mango']

# Adding elements to the list


fruits.append('pineapple')
print(fruits) # Output: ['apple', 'pear', 'orange', 'grape',
'mango', 'pineapple']

# Removing elements from the list


fruits.remove('orange')
print(fruits) # Output: ['apple', 'pear', 'grape', 'mango',
'pineapple']

# Checking if an element is in the list


print('banana' in fruits) # Output: False
print('grape' in fruits) # Output: True

Lists are not limited to holding only one data type; they can store elements of different types:
mixed_list = [1, 'apple', True, 3.14, [1, 2, 3]]

In addition to basic operations, Python provides a wide range of built-in functions and methods for
lists, making it easy to work with and manipulate list data. These functions and methods allow you to
sort lists, find the minimum and maximum values, concatenate lists, count occurrences, and more.
# Sorting a list
numbers = [5, 2, 9, 1, 5]
numbers.sort()
print(numbers) # Output: [1, 2, 5, 5, 9]
# Concatenating lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list1 + list2
print(result) # Output: [1, 2, 3, 4, 5, 6]

# Counting occurrences of an element


colors = ['red', 'blue', 'green', 'red', 'yellow', 'red']
print(colors.count('red')) # Output: 3

2 What is a Tuple
In Python, a tuple is another built-in data structure that is similar to a list but
with some key differences. Like lists, tuples are used to store collections of
elements. However, the main difference is that tuples are immutable, meaning
once they are created, their elements cannot be changed, added, or removed.
Tuples are defined using parentheses () and contain comma-separated elements. The elements can be
of different data types, just like in lists.
Here's an example of creating a tuple in Python:
# Creating a tuple
my_tuple = (1, 2, 3, 'hello', True)

# Accessing elements in the tuple using index


print(my_tuple[0]) # Output: 1
print(my_tuple[3]) # Output: hello

Tuples are commonly used to represent fixed collections of related items, such as coordinates (x, y) or
RGB color values (red, green, blue). Because of their immutability, tuples provide data integrity and
can be used as keys in dictionaries, which require hashable and immutable keys.
# Tuples as keys in dictionaries
point1 = (2, 3)
point2 = (5, 7)

points_dict = {point1: 'A', point2: 'B'}


print(points_dict) # Output: {(2, 3): 'A', (5, 7): 'B'}

While you cannot modify the elements of a tuple after its creation, you can perform operations that do
not alter the tuple itself. For example, you can create a new tuple by concatenating two or more
tuples:
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')

concatenated_tuple = tuple1 + tuple2


print(concatenated_tuple) # Output: (1, 2, 3, 'a', 'b', 'c')

You can also use tuples to conveniently swap the values of two variables:
a = 5
b = 10
a, b = b, a

print(a) # Output: 10
print(b) # Output: 5

3 What is a dictionary
In Python, a dictionary is a built-in data structure that represents an unordered
collection of key-value pairs. It is also known as an associative array or a hash
map in other programming languages. Unlike lists and tuples, which use
numerical indices to access elements, dictionaries use unique keys to access
their associated values. This makes dictionaries highly efficient for searching,
inserting, and deleting elements.
Dictionaries are defined using curly braces {} and consist of key-value pairs separated by colons :.
Each key in a dictionary must be unique, and it is used to access the corresponding value.
Here's an example of creating a dictionary in Python:
# Creating a dictionary
person = {
'name': 'John',
'age': 30,
'occupation': 'Engineer'
}

# Accessing values using keys


print(person['name']) # Output: John
print(person['age']) # Output: 30
print(person['occupation']) # Output: Engineer

You can also add, modify, and delete elements in a dictionary:


# Adding a new key-value pair
person['city'] = 'New York'

# Modifying the value of an existing key


person['age'] = 31

# Deleting a key-value pair


del person['occupation']

You can check if a key exists in the dictionary using the in keyword:

pythonCopy code
print('name' in person) # Output: True
print('gender' in person) # Output: False

Dictionaries are widely used in Python to store and manipulate data that requires quick access and
lookup based on unique keys. Some common use cases for dictionaries include representing JSON-
like data, configuration settings, and lookup tables.
It's important to note that starting from Python 3.7, dictionaries maintain the insertion order of
elements, which means that the order in which you insert elements into a dictionary is preserved when
you iterate over it. In earlier versions of Python, dictionaries were unordered, and their elements were
accessed randomly.
# Insertion order preserved in Python 3.7+
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
print(key, value) # Output: a 1, b 2, c 3

4 Explain Modules and Packages in Python


In Python, modules and packages are mechanisms to organize and structure
code, making it more maintainable, reusable, and easier to manage. They
facilitate the concept of modularity and help break down large codebases into
smaller, manageable components.
Module:
A module in Python is simply a file containing Python code, such as functions, classes, and variables.
The file can contain definitions, statements, and other Python constructs. By putting related code in
separate modules, you can logically organize your codebase and keep related functionality together.
To create a module, you create a Python script with the .py extension. For example, if you have a file
named my_module.py, it becomes a module that you can import and use in other Python scripts.

Example of a module (my_module.py):


# my_module.py

def greet(name):
return f"Hello, {name}!"

Using the module in another script:


# main.py

import my_module

message = my_module.greet("John")
print(message) # Output: Hello, John!

In this example, we import the my_module module in the main.py script and use the greet
function defined in the module.
Package:
A package in Python is a way to organize related modules into a single directory hierarchy. Packages
are collections of modules and can contain sub-packages as well. A package must include a special
file called __init__.py, which can be empty or contain Python code. The presence of
__init__.py signals to Python that the directory should be treated as a package.

Packages allow you to create a structured directory tree for your codebase and provide a convenient
way to group related functionality. They help prevent naming conflicts by allowing you to use
different package namespaces.
Example of a package structure:
my_package/
|-- __init__.py
|-- module1.py
|-- module2.py
|-- subpackage1/
| |-- __init__.py
| |-- module3.py
| |-- module4.py
|-- subpackage2/
|-- __init__.py
|-- module5.py

Using modules from a package:


# main.py

import my_package.module1
from my_package.subpackage1 import module3

result1 = my_package.module1.function1()
result2 = module3.function3()

print(result1)
print(result2)

In this example, we have a package named my_package that contains multiple modules. We import
module1 using the package name, and we import module3 directly from the subpackage1.

5 How many keywords are there in Python


As of Python 3.9, there are 35 keywords in Python. These keywords are reserved
and have specific meanings in the language. You cannot use them as identifiers
(variable names, function names, etc.) in your code.
Here is the list of Python keywords:

pythonCopy code
False await else import pass
None break except in raise
True class finally is return
and continuefor lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

6 Common built-in Data Types in Python


Python provides several built-in data types to store and manipulate different kinds
of data. Here are some of the most commonly used built-in data types in
Python:
1. Numeric Types:

 int: Integer type represents whole numbers, e.g., 5, -10, 100.


 float: Floating-point type represents decimal numbers, e.g., 3.14, -2.5, 0.0.
 complex: Complex type represents numbers with real and imaginary parts, e.g.,
2+3j, -1-4j.
2. Boolean Type:

 bool: Boolean type represents either True or False.


3. Text Type:

 str: String type represents a sequence of characters, enclosed in single quotes (' ') or
double quotes (" ").
4. Sequence Types:

 list: List is an ordered, mutable collection of elements, enclosed in square brackets


[ ].
 tuple: Tuple is an ordered, immutable collection of elements, enclosed in
parentheses ( ).
 range: Range represents an immutable sequence of numbers, often used for looping.
5. Set Types:

 set: Set is an unordered, mutable collection of unique elements, enclosed in curly


braces { }.
 frozenset: Frozenset is an unordered, immutable collection of unique elements,
enclosed in curly braces { }.
6. Mapping Type:

 dict: Dictionary is an unordered collection of key-value pairs, enclosed in curly


braces { }.
7. None Type:

 None: Represents the absence of a value or a null value.


8. File Type:

 file: Represents a file object used for reading, writing, or both.

7 Difference between PYTHON/JAVA


Python and Java are both popular programming languages, but they have some
key differences in terms of syntax, design philosophy, performance, and use
cases. Here's a comparison of some important aspects between Python and
Java:
1. Syntax and Readability:

 Python: Python has a clean and concise syntax that emphasizes readability and
simplicity. It uses indentation to define code blocks and avoids the need for explicit
braces. This results in code that is easy to understand and maintain.
 Java: Java has a more verbose syntax compared to Python. It uses curly braces to
define code blocks and requires semicolons at the end of statements. The syntax can
be more complex, especially for beginners.
2. Typing:

 Python: Python is a dynamically-typed language, which means you don't need to


specify variable types explicitly. The type of a variable is determined at runtime based
on the value assigned to it.
 Java: Java is a statically-typed language, which means you need to declare the data
type of a variable explicitly at the time of its declaration.
3. Performance:

 Python: Python is generally considered slower than Java in terms of execution speed.
It is an interpreted language, and some of its design choices for simplicity and
dynamic typing can impact performance.
 Java: Java is a compiled language and typically faster than Python due to the use of
Just-In-Time (JIT) compilers and optimizations. It is often used for performance-
critical applications.
4. Design Philosophy:

 Python: Python follows the "batteries-included" philosophy, providing a rich standard


library with many modules and tools for various tasks. It emphasizes code readability
and simplicity.
 Java: Java follows the "write once, run anywhere" (WORA) principle, which allows
Java code to be executed on any platform with a Java Virtual Machine (JVM). It is
known for its robustness, portability, and scalability.
5. Community and Ecosystem:

 Python: Python has a strong and active community with a vast ecosystem of libraries
and frameworks. It is widely used in web development, scientific computing, data
analysis, machine learning, and more.
 Java: Java also has a large and active community with a rich ecosystem. It is often
used in enterprise applications, Android app development, big data processing, and
server-side applications.
6. Learning Curve:

 Python: Python is considered easy to learn and is often recommended for beginners
due to its simplicity and readability.
 Java: Java has a steeper learning curve compared to Python, mainly because of its
verbose syntax and stricter typing rules.
8 Which is faster JAVA or Python
In general, Java is faster than Python in terms of execution speed. There are
several reasons for this performance difference:
1. Compilation vs. Interpretation:

 Java: Java is a compiled language. Java source code is first compiled into bytecode,
which is platform-independent. This bytecode is then executed by the Java Virtual
Machine (JVM) at runtime. The JVM can perform various optimizations during the
execution, leading to improved performance.
 Python: Python is an interpreted language. Python source code is executed line by line
by the Python interpreter, which interprets the code at runtime. This interpretation
process can introduce some overhead, making Python generally slower than Java.
2. Static Typing vs. Dynamic Typing:

 Java: Java is statically typed, which means that variable types must be declared
explicitly at compile time. This allows the compiler to perform type checks and
optimizations, resulting in more efficient code.
 Python: Python is dynamically typed, which means that variable types are determined
at runtime. This dynamic typing can introduce some overhead as the interpreter needs
to perform type checks during execution.
3. Optimizations and Just-In-Time (JIT) Compilation:

 Java: Modern Java implementations, such as HotSpot JVM, use Just-In-Time (JIT)
compilation to convert bytecode into native machine code on the fly. JIT compilation
allows Java to make runtime optimizations and adapt the code for the specific
hardware it is running on, leading to better performance.
 Python: Python's CPython implementation (the standard and most widely used
implementation) does not have JIT compilation. While there are alternative
implementations like PyPy that use JIT, CPython remains the most commonly used
and is generally slower than Java's JIT-compiled code.
4. Language Features and Abstractions:

 Python: Python's design philosophy prioritizes simplicity and readability, which can
result in more straightforward code but may sacrifice some performance
optimizations.
 Java: Java's design philosophy prioritizes performance, robustness, and portability,
which can lead to more verbose code but with better performance characteristics.

9 What is break, continue and Pass in Python


In Python, break, continue, and pass are control flow statements that allow you
to control the flow of execution in loops and conditional statements.
1. break:

 The break statement is used to exit or terminate the current loop prematurely. When
the break statement is encountered inside a loop (e.g., for loop or while loop),
the loop is immediately terminated, and the program continues with the next
statement after the loop.
 break is often used to exit a loop early when a specific condition is met, or when
you want to stop the loop based on certain criteria.
 Example:

for i in range(1, 6):


if i == 3:
break
print(i)
# Output: 1 2

2. continue:

 The continue statement is used to skip the rest of the current iteration of a loop and
proceed to the next iteration. When the continue statement is encountered inside a
loop, the loop does not execute the remaining code for that iteration but continues
with the next iteration.
 continue is often used to skip certain iterations based on specific conditions.
 Example:

for i in range(1, 6):


if i == 3:
continue
print(i)
# Output: 1 2 4 5

3. pass:

 The pass statement is a null statement in Python. It does nothing when executed and
is used as a placeholder where syntactically some code is required, but you don't want
to add any functionality yet. It is often used as a temporary stub while developing
code or as a placeholder for future implementation.
 pass is useful when you need to write an empty code block to avoid syntax errors.
 Example:

for i in range(1, 6):


if i == 3:
pass
else:
print(i)
# Output: 1 2 4 5

10 What is slicing in Python


Slicing in Python refers to the technique of extracting a portion (subsequence) of
a sequence (string, list, tuple) by specifying start and end indices. It allows you
to create a new sequence containing elements from the original sequence within
the specified range. The resulting subsequence is a copy, and the original
sequence remains unchanged.
The syntax for slicing is sequence[start:stop], where:

 sequence is the original sequence (string, list, or tuple).


 start is the index where the slicing begins (inclusive).
 stop is the index where the slicing ends (exclusive).

Here are some examples of slicing in Python:


1. Slicing a String:
text = "Hello, World!"
sub_text = text[0:5] # Extracting characters from index 0 to index
4 (5 is exclusive)
print(sub_text) # Output: "Hello"

sub_text = text[7:] # Extracting characters from index 7 to the


end
print(sub_text) # Output: "World!"

sub_text = text[:5] # Extracting characters from the beginning to


index 4 (5 is exclusive)
print(sub_text) # Output: "Hello"

2. Slicing a List:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sub_list = numbers[2:6] # Extracting elements from index 2 to index
5 (6 is exclusive)
print(sub_list) # Output: [3, 4, 5, 6]

sub_list = numbers[:4] # Extracting elements from the beginning to


index 3 (4 is exclusive)
print(sub_list) # Output: [1, 2, 3]

sub_list = numbers[6:] # Extracting elements from index 6 to the


end
print(sub_list) # Output: [7, 8, 9, 10]

3. Slicing a Tuple:
my_tuple = (10, 20, 30, 40, 50)
sub_tuple = my_tuple[1:4] # Extracting elements from index 1 to
index 3 (4 is exclusive)
print(sub_tuple) # Output: (20, 30, 40)

sub_tuple = my_tuple[:3] # Extracting elements from the beginning


to index 2 (3 is exclusive)
print(sub_tuple) # Output: (10, 20, 30)

sub_tuple = my_tuple[2:] # Extracting elements from index 2 to the


end
print(sub_tuple) # Output: (30, 40, 50)
11Explain about decorators in python
In Python, a decorator is a powerful and flexible feature that allows you to modify
or extend the behavior of functions or methods. Decorators are often used to
add functionality to existing functions without modifying their code directly. They
are implemented using the concept of higher-order functions, where functions
can take other functions as arguments and return them as results.
A decorator is denoted by the @decorator_name symbol above the function definition. When a
function is decorated, it is passed as an argument to the decorator function, which then returns a new
function or modifies the original function.
Here's a simple example of a decorator:
# Decorator function
def my_decorator(func):
def wrapper():
print("Something is happening before the function is
called.")
func()
print("Something is happening after the function is
called.")
return wrapper

# Function to be decorated
def say_hello():
print("Hello!")

# Decorating the function using the decorator


say_hello = my_decorator(say_hello)

# Calling the decorated function


say_hello()

Output:
Something is happening before the function is called.
Hello!
Something is happening after the function is called.

In the above example, my_decorator is a decorator function that takes say_hello as an


argument and returns a new function called wrapper. The wrapper function contains the added
functionality that executes before and after calling say_hello. When we call say_hello() after
decoration, it is actually executing the wrapper function, which then calls the original say_hello
function inside it.
Python provides a more convenient syntax to apply decorators using the @decorator_name
symbol directly above the function definition:
@my_decorator
def say_hello():
print("Hello!")
This is equivalent to manually applying the decorator as shown in the first example.
You can also create decorators with arguments to make them more flexible:
def repeat(num_times):
def my_decorator(func):
def wrapper():
for _ in range(num_times):
func()
return wrapper
return my_decorator

@repeat(num_times=3)
def say_hello():
print("Hello!")

say_hello()

Output:
Hello!
Hello!
Hello!

You might also like