CTA
Table of contents
1. Python Basic Interview Questions For Freshers
2. Python OOPS Interview Questions & Answers
3. Advanced Python Technical Coding Questions
Frequently Asked Python Interview Questions
1. What do you mean by Python being an Interpreted language?
2. What is the difference between slicing and indexing?
3. How does python handle argument passing: by reference or by value?
4. What is the significance of self in Python classes?
5. How do you find the middle element of a linked list in one pass?
6. What are collections? What is the significance of collections in Python?
7. What is the difference between %, /, //?
8. Explain the difference between pickling and unpickling.
9. What is Experimental Just-in-Time (JIT) Compilation in Python
10. What are Access Specifiers in Python?
Python Basic Interview Questions For Freshers
1. What makes Python different from other languages?
Python is the most used programming language in the world. Here are the top reasons for the same:
- Python is a Dynamic Programming Language – you don’t have to declare variables before using them and memory allocation and de-allocation is also handled automatically.
- Interpreted – In Python, code is executed line-by-line rather than compiling the entire code and then executing it.
- High-Level Language – Python automatically manages many things for you, like memory, cross-compatibility, etc.
- Easy Syntax – Python follows simple syntax, having high readability. Let’s compare printing simple hello world statements in Python and Java.
Python: print(“Hello World”)
Java:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
2. What do you mean by Python being an Interpreted language?
An interpreter allows the code to run line by line rather than being compiled into machine code first. Rather than compiling the code first and then executing it, compilation and execution happen simultaneously in Python, saving time.
Example:
print("This line will be executed first.")
print("This line is executed without any issues.")
print("This line will run.")
variable # This will throw an error since the variable is not defined
print("This line will not execute due to the error above.")
3. Give three differences between Lists and Tuples.
Both Lists and Tuples are used to store collections of items, but they differ in meaningful ways.
- List
- Uses square brackets []
- Mutable
- Use more memory because it is dynamic
- Better with insertion & deletion operations
- Slower iteration
- Supports more methods and operations due to its mutable nature. E.g. append, pop, remove
- [‘a’, 1, “abc”]
- Tuple
- Uses parentheses ()
- Immutable
- Use lesser memory because it’s static
- Better for accessing elements
- Faster iteration
- Lesser built-in methods due to its immutable nature
- (‘a’, 1, “abc”)
4. Differentiate between Mutable and Immutable data types.
- Definition: Can be modified after their creation
- Data Types: Lists, Dictionaries, Sets
- Use Case: Where data requires frequent updates.
- Example:
l = ['a', 'b', 'c', 'd']
# modifying element at index 1
l[2] = 'g'
# Appending and deleting an element from the list
l.pop(0)
l.append('z')
print(l)
Output >> ['b', 'g', 'd', 'z']
- Immutable
- Definition – Cannot be modified once the data type is created
- Data Types – Tuples, Strings, Integers, Floats
- Use Case – Where we need to store data that will stay the same.
- Example –
t = ('a', 'b', 'c', 'd')
# modifying element:
t[2] = 'g'
Output >> 'tuple' object does not support item assignment.
5. What is the difference between slicing and indexing?
Slicing and indexing are both ways of accessing elements in sequences, like lists or strings, but they work differently.
- Slicing:
- Definition: Refers to accessing a range of elements, like cutting out a portion of the sequence.
- Syntax: List[start: stop: step value]
- Example:
l = [10, 20, 30]
print(l[:2])
Output >> [10, 20]
- Indexing:
- Definition: Refers to a specific item in a sequence by its position or index.
- Syntax: List[index value]
- Example:
l = [10, 20, 30]
print(l[0])
Output >> 10
6. Explain list comprehension
- List comprehension allows you to create new lists using a one-line syntax.
- It’s a compact and readable alternative to using a traditional for loop.
- A new list can be generated based on an existing one by applying conditions or transformations within a single line.
Example:
# squaring even numbers
l = [i**2 for i in range(5) if i%2==0]
print(l)
7. What is the difference between break and continue?
The Break and Continue flow statements determine how and when certain sections of the code will be executed or skipped.
- Break:
- Definition: It terminates the loop inside which it is used and moves the control to the statement that follows the loop.
- Scenario: Stopping the movie midway and then continuing with the task that you would perform in normal conditions.
- Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
# implementing the break statement:
for num in numbers:
if num == 5:
print("Found 5! Exiting the loop.")
break
print(num)
Ouput >> 1
2
3
4
Found 5! Exiting the loop.
- Continue:
- Definition: This terminates the current iteration of the statement and transfers the control flow to the next iteration of the loop.
- Scenario: Skip a part of the movie, but watch the rest
- Example:
# implementing the continue statement:
print("continue statement:")
for num in numbers:
if num ==5:
continue # Skip the number 5
print(num)
Output >> continue statement:
1
2
3
4
6
7
8
8. What is the Pass statement?
- The pass statement is used to fill up an empty block.
- It is a placeholder; it doesn’t perform any action when executed.
- It’s often used when writing code and wanting to leave a specific section empty for now, but don’t want to run into errors. In Python, an empty block of code will raise an error, so a pass statement helps to avoid that.
- It is a no-operation statement.
Example:
for number in range(5):
if number < 3:
pass # Placeholder for future code
else:
print(f"Number is {number}")
Output >> Number is 3
Number is 4
9. What do you understand by scope?
The Scope is the area in a program where a variable or a function is accessible. Simply put, it tells where to use or interact with a particular variable or function.
There are 2 types of scopes:
- Global:
- Definition: When a variable is defined outside of any function or block, it’s accessible from anywhere in the code.
- Example: A book that is placed on a public shelf so that anyone in the library can access it
- Local:
- Definition: When a variable is defined within a function, it can only be accessed inside that function
- Example: A book kept in the individual drawer is accessed by only the owner.
10. What are negative indexes, and why are they used?
- Negative indexes allow you to access elements from the end of a sequence, such as a list or a string, rather than from the beginning.
- It’s like counting backward instead of forward.
- Typically, when you use a positive index, you access elements from the start, with 0 being the first element.
- Negative indexes allow you to access elements at the end without calculating the length.
Example:
l = ["alice", "bob", "charlie", "david", "Emmanuel", "fiona"]
print(l[-2])
Output >> Emmanuel
11. How do you copy an object in Python?
Mainly, there are 3 ways of copying an object in Python
- Assignment Operator (=)
The assignment operator does not copy an object. Rather, it creates a new reference that points to the same object in memory.
- Shallow Copy
- This method will copy only the object’s surface, i.e., any nested objects, say lists within a list, will only be copied as a reference. In contrast, the other elements outside any nested object will be copied.
- If the surface elements in the original object are changed, they are independent.
- If the nested elements are modified, the change will reflect in both the copied and original objects.
- Deep Copy
- This method creates an independent copy of the original object, including all the nested objects.
- Any modifications in the deep copy do not affect the original object and vice versa
Example:
import copy
l = [10, 20, [1, 2, 3], [4, 5, 6]]
# Shallow copy
shallow_l = copy.copy(l)
# Deep copy
deep_l = copy.deepcopy(l)
l[0] = 250
l[2][0] = 'X'
print("Original List:", l)
print("Shallow Copied List:", shallow_l)
print("Deep Copied List:", deep_l)
Output >>
Original List: [250, 20, [‘X’, 2, 3], [4, 5, 6]]
Shallow Copied List: [10, 20, [‘X’, 2, 3], [4, 5, 6]]
Deep Copied List: [10, 20, [1, 2, 3], [4, 5, 6]]
12. What does *args and **kwargs mean?
*args and **kwargs are passed as parameters in functions that help handle various arguments.
*args |
**kwargs |
Allows to pass any number of positional arguments to a function. |
Allows you to pass a variable number of arguments in a key-value pair |
Stores all the extra positional arguments in a Tuple |
Stores them in a Dictionary |
Example:
# defining a function with a variable number of arguments.
def test(*args, **kwargs):
print("Positional arguments (args):")
for arg in args:
print(arg)
print("\nKeyword arguments (kwargs):")
for key, value in kwargs.items():
print(f"{key}: {value}")
test(1, 2, 3, name="Alice", age=30, city="New York")
# passing normal arguments and keyword arguments in the function test.
13. How does python handle argument passing: by reference or by value?
In Python, argument passing is done using “pass by object’s reference” or “call by sharing”
Let’s understand, what this means:
When an argument is passed to a function in Python, the argument is pointing to an object.
For example, a string integer or list.
When we call the function, the object’s reference is passed, and not the actual object.
However, this behavior differs based on the mutability of the object.
If the object is mutable for example: a list, the reference to the actual object is passed. Hence, if the function modifies the object, the original object also gets modified.
Code Example:
# Define a function that modifies a list
def modify_list(my_list):
my_list.append(4) # Add an element to the list
print("Inside function:", my_list)
# Create a mutable object (list)
original_list = [1, 2, 3]
# Pass the list to the function
modify_list(original_list)
# Check the list outside the function
print("Outside function:", original_list)
Output:
Inside function: [1, 2, 3, 4]
Outside function: [1, 2, 3, 4]
As you can see from the example, the values of the object outside the function and inside the function change.
However, if the object is immutable, for example, an integer, if a change is made to the referenced object, the original object remains unaltered. However, a copy of the object is made inside the function and change happens to it. But the original object, that is outside the function the object’s value remains unaltered.
Example:
# Define a function that tries to modify an integer
def modify_integer(num):
num += 10 # Reassigning to a new integer object
print("Inside function:", num)
# Create an integer (immutable object)
original_number = 5
# Pass the integer to the function
modify_integer(original_number)
# Check the integer outside the function
print("Outside function:", original_number)
Output:
Inside function: 15
Outside function: 5
As you can see, the value of the object inside the function is different, however, the value of the object outside the function remains unaltered.
14. What is lambda in Python? Why is it used?
A lambda function is a small anonymous function, which does not have a name. It can have any number of arguments but has only one expression.
It is also referred to as a “single-line function”.
For example:
# Lambda function to add two numbers
add = lambda x, y: x + y
# Using the lambda function
result = add(3, 5)
print(result) # Output: 8
It is used for the following reasons:
- It is compact and simple to write
- It is usually used for short-lived functions, which will not used anywhere else in the code.
- To improve the readability of the code
15. Explain exception handling in Python.
- The ‘TRY’ block wraps all the risky code
- Risky code is a piece of code that has the potential to throw an error. Eg. dividing by zero, syntax error.
- In case of an error, the ‘EXCEPT’ block is executed
- If no error occurs, the ‘ELSE’ block is executed
- The ‘FINALLY’ block executes no matter what.
Example:
try:
number = int(input("Enter a number: "))
result = 10 / number
except ZeroDivisionError:
print("You cannot divide by zero!")
else:
print("Result is:", result) # Executes if no exception occurs
finally:
print("Execution completed.") # Always executes
16. How is memory managed in Python?
The process of managing memory is done automatically in Python by the Garbage Collector and Heap Space.
- Garbage collection: Garbage collector is a built-in feature in Python that identifies and clears circular references automatically Circular References are when two objects refer to each other but aren’t needed by the program.
- Private heap: Private Heap contains all the Python objects and data structures.
- Reference counting: Every object in Python has a reference count, which tracks how many variables or objects refer to that object. When the reference count drops to zero Python frees up the memory for that object.
- Memory Pools: Python uses a system of memory pools to optimize the allocation and deallocation of smaller objects. It improves performance.
17. Differentiate between Sorted vs sort
Sort and Sorted are the two built-in methods used to sort objects in Python. However, their features differ in some aspects that we’ve covered below.
|
Sorted |
Sort |
Definition |
Returns a new list |
Modifies the list in place |
Scope |
Works on any iterable |
Works only on lists |
Syntax |
sorted(iterable, key=None, reverse=False) |
list.sort(key=None, reverse=False) |
Example |
l = [1,45, 7, 34, 56]
sorted_l = sorted(l)
print(sorted_l)
>>[1, 7, 34, 45, 56]
print(l)
>>[1, 45, 7, 34, 56] |
l = [1,45, 7, 34, 56]
l.sort()
print(l)
>> [1, 7, 34, 45, 56] |
18. What is compile time and runtime error? Do they exist in Python?
Compile time error and runtime error are the two errors that happen in Python at different stages of the execution of the program.
|
Compile Time Error |
Runtime Error |
Definition |
Mistakes that are caught before the program runs. |
These are the errors that happen while your code is running after the syntax is checked and the program has started to execute. |
Type of error |
The errors identified at compile time are usually related to syntax |
The errors identified at runtime usually occur because something unexpected happened during the execution of the program that the Python interpreter wasn’t prepared for. |
Real-life Analogy |
You’re typing up an email and the spell checker underlines mistakes for you as you type |
You’re driving on a smooth road and suddenly hit a bump or a pothole |
Example |
x = 0
if x > 10 # Missing colon
print(“x is greater than 10”) |
number = 5
text = “hello”
result = number + text
>> TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’ |
Do they exist in Python?
Yes, both types of errors exist in Python, but instead of using the term “compile-time error”, syntax errors are used more commonly in Python because these errors are caught when the interpreter is going through the code line by line and encounters a piece of code that doesn’t follow the syntax. Everything else is handled as runtime errors in Python. It includes errors like type errors, index errors, or exceptions that are only detected once the code is running.
19. What are generators and decorators?
Generators and Decorators are two methods used in Python to modify functions in a way that the code becomes more readable and efficient. However, they are used for completely different purposes.
- Generators are functions that return an iterator. Using this iterator, you can iterate over the values one at a time.
- They use the yield method instead of the return method usually used in functions
- Useful when dealing with large datasets or infinite sequences
- Generator functions remember their state between each yield.
Example:
def countdown(num):
while num > 0:
yield num
num -= 1
# Using the generator
for count in countdown(5):
print(count)
Output>>
5
4
3
2
1
- Decorators are functions that modify an existing function or class.
- They extend the behavior or properties of the existing functions or classes without changing the code.
- Decorator functions take a function as an argument, add some behavior to it, and return the new function with modified or extended behavior.
- Useful in cases like logging, authentication, or timing how long a function takes to run.
Example:
def decoratorFunc(func):
def wrapper():
print("Before the function is called.")
func()
print("After the function is called.")
return wrapper
@decoratorFunc #greet = decoratorFunc(greet)
def greet():
print("Hello!")
# Calling the decorated function
greet()
Output>>Before the function is called.
Hello!
After the function is called.
20. What is the difference between abstraction and encapsulation?
Abstraction and encapsulation are both a part of the 4 pillars of object-oriented programming, but they serve different purposes.
|
Abstraction |
Encapsulation |
Definition |
Hides the complexity of the system by showing only the essential details to the users. |
Restricts access to certain parts of an object to protect its details. |
Functionality |
Focuses on what an object does rather than how it does it |
Hides the internal details of an object by bundling the data or the attributes and the methods into a single unit, or class and making the attributes private. |
Application |
Users are exposed to the fact that pressing the brake pedal will stop the car rather than how the brake pedal stops the car. |
Similarly, all the internal mechanisms of the car are protected by making attributes like speed private so that they cannot be accessed publicly. |
Example |
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print(“Bark”)
animal = Dog()
animal.make_sound() |
class Car:
def __init__(self):
self.__speed = 0 # Private attribute
def accelerate(self, value):
self.__speed += value
def get_speed(self):
return self.__speed
car = Car()
car.accelerate(10)
print(car.get_speed()) |
21. What is method overriding? How is it different from method overloading?
Method overriding and method overloading are two ways to achieve Polymorphism in object-oriented programming, but they work in different ways.
Method Overriding |
Method Overloading |
When a subclass provides a different implementation of a method that is already defined in its parent class. In other words, the child class overrides the behavior of the parent class’s method. |
Allows you to define several methods, each designed to handle a different number of inputs. |
class Animal:
def speak(self):
return “Some sound”
class Dog(Animal):
def speak(self):
return “Bark” # Dog overrides the speak method
dog = Dog()
print(dog.speak()) # Output: Bark |
class Math:
def add(self, a, b, c=0):
return a + b + c
# Different behavior based on the number of arguments
print(Math().add(2, 3)) # Output: 5
print(Math().add(2, 3, 4))
# Output: 9 |
22. How does inheritance work in Python?
Inheritance is one of the 4 pillars of Object Oriented Programming. Inheritance allows one class to inherit aspects like attributes and methods from another class.
- The class that inherits is called the child class or sub-class
- The class from which the attributes are inherited is called the parent class or superclass
- On performing inheritance, the child class gets access to all the attributes and methods of the parent class.
- The child class can override, extend, or modify the methods of the parent class, promoting code reuse.
Example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
class Dog(Animal): # Dog class inherits from Animal
def speak(self):
return f"{self.name} barks." # Using the classes
dog = Dog("Buddy")
print(dog.speak()) # Output: Buddy barks
23. What is the significance of self in Python classes?
In Python, the self keyword acts as a bridge that connects an instance of a class with its methods and attributes.
- Whenever you create an object from a class you need a way to refer to that specific object inside the class’s methods.
- Real-life scenario: Employees have their names written on their badges. The self keyword is like the employee’s badge.
- Self refers to the object that calls the method, mapping the data with each object to specify the object’s data.
Example:
class Employee:
def __init__(self, name, position):
self.name = name # refers to the instance's name
self.position = position # refers to the instance's pos
def greet(self):
print(f"Hi, I’m {self.name} and I work as a {self.position}.")
# Create an instance of Employee
emp1 = Employee("John", "Manager")
# When you call greet(), Python automatically passes `emp1` as `self`
emp1.greet()
24. What are class methods and static methods? How are they different from instance methods?
Class methods, Static methods, and Instance methods are three different methods that follow different methods to interact with the class and its instances.
- Class Methods
- Class Methods deal with the class itself
- They can modify the class-level attributes but not the objects or their instances.
- Class methods take “cls” as their first parameter rather than “self”, which refers to the class itself.
- Class methods are defined using the decorator @classmethod. This tells Python that the method works with the class rather than an instance.
Example:
class Dog:
species = "Canine" # Class-level attribute
def __init__(self, name, breed):
self.name = name
self.breed = breed
@classmethod
def change_species(cls, new_species): # Class method
cls.species = new_species # Modifies class-level attribute
Dog.change_species("Feline")
print(Dog.species) # Outputs: Feline
- Static Methods:
- Static methods do not depend on any instance or class-specific data
- They are normal functions that are included inside the class for better code readability.
- Static methods are defined using the @staticmethod decorator
- They do not require any keyword like self or cls as their first parameter.
- Useful for implementing logic for a class but requires no access to the class or instance data.
Example:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
@staticmethod
def dog_age_in_human_years(dog_age): # Static method
return dog_age * 7
print(Dog.dog_age_in_human_years(4)) # Outputs: 28
- Instance Methods
- Instance methods take self keyword as their first parameter
- They are used to access instance-specific data (attributes)
- They work with the individual object’s data
Example:
class Dog:
def __init__(self, name, breed):
self.name = name # Instance attribute
self.breed = breed
def bark(self): # Instance method
print(f"{self.name} says woof!")
my_dog = Dog("Buddy", "Golden Retriever")
my_dog.bark() # Calls the instance method
25. Explain the differences between a set and a dictionary.
Set and Dictionary are both built-in data structures for storing and managing data.
|
Sets |
Dictionary |
|
|
|
Structure |
Elements are unordered but unique
E.g.: t = {1, 2, 3}) |
Stores data in the form of key-value pairs
E.g.: dict = {“a”: 1, “b”: 2} |
Purpose |
When you need a collection of unique items and don’t care about the order.
E.g.: collecting unique words from a text. |
When you need to map one item to another.
E.g.: storing people’s names (keys) against their phone numbers (values). |
Accessing elements |
You cannot access a particular element through indexing due to its unordered nature. |
Values can be accessed through the keys associated to the respective values. |
Example |
s = {1, 2, 3, 4, 5} # unique numbers
print(s)
s.add(6)
s.add(3)
print(s)
# {1, 2, 3, 4, 5, 6} |
dict = {
“name”: “Alice”,
“age”: 30,
“city”: “New York”
}
print(dict[“name”]) # Output: Alice
dict[“age”] = 31
print(dict) |
26. You are given a singly linked list that stores integer values in ascending order. Your task is to determine the time complexity for performing an insertion operation on numeric value 6 in the given LinkedList.
head -> 2 -> 5 -> 8 -> 12 -> None
The two main steps involved in an insertion operation in a singly LinkedList are Traversing and Inserting
- Traversing: Firstly, you need to find the right place to insert the element, which is between 5 and 8 in our case. Starting from the “head” node you will traverse node by node till you find the location. The time complexity for this operation will depend on the number of nodes.
- Comparing: As you traverse through the nodes, you have to compare each node with the element you want to insert. If the element is smaller than the current node element, you will insert the new node else move to the next node. This process is repeated until you reach the end of the list and it will have a complexity of O(1).
- Inserting: Once you have located the position where you want to insert, you will adjust the pointers in a way such that your previous node which is the node containing 5, will have the next pointer pointing to the new node containing 6.You then need to point the next pointer of your new node to the node containing 8.
This operation also requires a constant time i.e.: O(1)
So now that we have the time complexity of comparing the node with our element and inserting the new node, let us also find the time complexity of traversing the list.
If the position is the very first node you traverse to, your time complexity will be O(1), which is known as the Best Case scenario.
But this scenario is very rare and we have to consider something something more general. This is why we consider the worst case scenario. Here we assume that the node is inserted at the end of the list. So in this case we will have to traverse the entire list and our time complexity will turn out to be O(n) where n is the number of nodes in the list.
But since the dominant factor here is the traversing operation, since the insertion operation and the comparing operation do not depend on the size of the list and always have a constant time complexity.
So the overall time complexity of inserting an element in the LinkedList at a random position is O(n).
27. How do you find the middle element of a linked list in one pass?
Here the main catch in the question is “one pass”. What does it mean? It means you get to traverse the list only once and there’s no coming back to a node once you’ve traversed it. But to calculate the middle element you will require the length of the entire LinkedList, right?
So this is where the Two-Pointer Technique also known as the Slow and Fast Pointer method.
You will have 2 pointers one moving twice as fast as the other. In other words, the fast pointer will skip a node and jump to second node when the slow pointer The main logic behind having the two pointers is that at the time the fast pointer reaches the end of the list, the slow pointer will be at the middle node.
Now the question here is that how do we know that the fast pointer has reached the end of the list?
This is implemented through the logic “while fast and fast.next” which basically means that we will iterate through the list only if our fast pointer is not null.
So the moment the fast pointer reaches the null node, the condition remains unsatisfied and the loop is terminated.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, new_data):
new_node = Node(new_data)
if not self.head:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
def find_middle(self):
slow = self.head
fast = self.head
while fast and fast.next:
slow = slow.next # Move slow by one step
fast = fast.next.next # Move fast by two steps
return slow.data
# Example usage:
ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.append(4)
ll.append(5)
middle_element = ll.find_middle()
print(f"The middle element is: {middle_element}") # Output: 3
Edge Case:
Even number of nodes: If the list has an even number of nodes, you will have to explicitly decide what “middle” means for your problem because you will have two middle elements in the list. You can return either of the two elements depending on the problem and sample outputs provided.
28. You have a string, and you want to find the length of the longest substring of that string where no characters repeat. For example, in the string
For implementation-based questions like this one, the interviewer is not looking if you can write a code for the problem but rather if you can come up with an optimized solution and get the logic right for it.
Your first instinct would be to blurt out the answer saying “Generate all the possible substrings and then look for the substring having all unique characters and also the maximum length.”
This approach is not wrong but as we mentioned, this is not what the interviewer is looking for.
The right answer would be an optimized logic like the Sliding Window where you would explain the main concepts like:
- Two Pointers: You would use two pointers, left and right, which represent the start and end of your current window or substring. Your right pointer will be traversing the characters of the string one at a time, expanding your window or your substring.
- Track Seen Characters: To check for duplicates, you will need a hashmap or a dictionary to store all the characters in the current window along with their index values.
Every time your right pointer moves to the next index, you have to check whether the character is already present in your dictionary.
If it is present it is a duplicate character and now instead of incrementing the right pointer, you will increment the left pointer by 1 plus the index value of the duplicate character where it occurred last.
If it is not a duplicate character, you will add it to the dictionary and increment your right pointer.
At this point, our dictionary or hashmap will look something like this:
a -> 0 3
b -> 1 4
c -> 2 5
d ->
Looking at this map, you should be able to figure out that lastly, d will get mapped with index 6 and since it is not a repeating character, our maximum length will get updated to 4 and hence we get our final answer.
- Check for Maximum Length: Each time you adjust the window containing all unique elements, you need to check if the length is greater than your previous window length. The formula for it is max(max_len, right – left + 1).
def lengthOfLongestSubstring(s):
max_len = 0
left = 0
char_count = {}
for right in range(len(s)):
current = s[right]
if(current in char_count.keys() and char_count[current] >= left):
left = char_count[current] + 1
max_len = max(max_len, right-left+1)
char_count[current] = right
return max_len
s = "abcabcd"
print(lengthOfLongestSubstring("abcabcd"))
29. You're given a set of items, each with a weight and value. You are required to figure out how to pack the most valuable items into a knapsack without exceeding its weight limit, where each item can either be taken or left behind.
This problem is also known as 0/1 Knapsack problem. You are given a Knapsack with a certain weight limit or capacity. Keeping this capacity in mind, you need to fill the items in your knapsack in such a way that you maximize the total value of the items.
We will not look at the Brute Force approach but rather directly dive into the optimized solution which will be achieved using Dynamic Programming.
We will understand this with the help of an example.
We are given 4 items, where List A gives the price of the items and List B gives the weights of the items respectively and variable C gives the capacity of the bag or the knapsack.
Price (A) = {1, 2, 5, 6}
Weights (B) = {2, 3, 4, 5}
Bag capacity (C) = 8
|
|
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
Profit |
Weight |
0 |
0 |
0 |
0 |
0 |
0 |
0 |
0 |
0 |
1 |
2 |
0 |
0 |
1 |
1 |
1 |
1 |
1 |
1 |
1 |
2 |
3 |
0 |
0 |
1 |
2 |
2 |
3 |
3 |
3 |
3 |
5 |
4 |
0 |
0 |
1 |
2 |
5 |
5 |
6 |
7 |
7 |
6 |
5 |
0 |
0 |
1 |
2 |
5 |
6 |
6 |
7 |
8 |
We will create a table where rows (i) represent each item, and columns (j) represent different possible weight capacities up to the maximum weight. Let’s call this table V. Here, V[i][j] will represent the maximum value that can be achieved with the first i items and a weight limit of j.
Initialize the Table:
- If no items are chosen (i.e., i = 0), the maximum value for any weight w is 0 because there are no items to include.
- If the weight limit is 0, the maximum value is also 0 because the knapsack can’t hold anything.
Fill in the Table:
- If the item’s weight is greater than j, we can’t include it, so V[i][j] = V[i-1][j]
- If the item’s weight is less than or equal to w, you have two options:
- Exclude the item: V[i][j] = dp[i-1][j]
- Include the item: dp[i][j] = value[i] + dp[i-1][j – weight[i]]
- You need to find the maximum value out of the two options because the maximum one is going to be more profitable.
V[i,j] = max{V[i-1,j], V[i-1, j-wi] + Pi}
Find the result: After filling out the table, the answer will be in V[n][W], which is the last cell of the table. Here, n is the number of items and W is the knapsack’s weight limit. This cell gives the maximum profit that can be achieved using the items given and keeping in mind the knapsack’s weight limit.
30. You are given a series of asteroids moving in a line; when they collide, they either destroy each other or continue moving. You have to determine the final state of all the asteroids after all collisions.
You will be given a list of integers representing the magnitudes of the asteroids. An integer having positive magnitude is considered to be moving in the right direction whereas a negative magnitude asteroid moves in the left direction.
We will use a stack data structure, to keep track of asteroids that haven’t yet collided and in the end, we will just return the stack representing the final state of the asteroids left or the asteroids that did not get destroyed after all the collisions.
- Iterate Through Each Asteroid:
- If an asteroid is moving right (positive), add it to the stack since there’s no chance of a collision
- If an asteroid is moving left (negative), check for a collision with the asteroid at the top of the stack
- Handle Collisions:
- If the stack is not empty and the top of the stack element is moving right:
- If the left-moving asteroid has a greater magnitude than the top of the stack element, the top of the stack element will get popped from the stack since it has been destroyed. The collision will continue with the next asteroids.
- If the right-moving asteroid has a greater magnitude, it will destroy the left-moving asteroid. We simply move to the next asteroid.
- If they’re equal in magnitude, both the asteroids get destroyed, i.e.: we pop the top of the stack element and also move on to the next asteroid.
- Continue this process until there are no more asteroid collisions.
- Result:
- After iterating through all the asteroids, all the asteroids that survived the collisions are in the stack. These are the final asteroids remaining after all the collisions.
E.g: You are given a list of asteroids: [ 5, 10, -5, -15]
We will iterate through the list of asteroids and check for collisions one by one. Since our stack is empty, we add the first asteroid we come across in the stack, which is 5. Then we move to the next asteroid which is 10. Since 5 and 10 are moving in the same direction, there will not be any collision and hence 10 will also be pushed in the stack.
Then we go ahead and compare the next asteroid which is -5 and the top of the stack element -> 10. Since they are moving in opposite direction and 10 is greater in magnitude than -5, -5 asteroid will get destroyed. So we simple move to the next asteroid skipping the current asteroid (-5)
Then we go ahead and compare the next asteroid which is -15 with the top of the stack element (10). Since -15 is greater in magnitude than 10, the top of the stack element, 10, will get destroyed which means we will pop the element.
Then we compare our new top of the stack element, which is 5 with -15. Since -15 again has a greater magnitude than 5, we will pop the element since it will get destroyed.
Finally, we will be left with -15 element in the stack. We will return the stack as our final output which shows the final state of all the asteroids after the collisions. In our case, we are only left with -15 which means, one asteroid having magnitude 15 moving in the left direction.
CTA
31. What is Python, and how does its dynamic typing work?
Python is a high-level, general-purpose programming language developed by Guido van Rossum in 1991. It utilizes English keywords extensively and has a simpler syntax as compared to multiple other programming languages. It’s a dynamically typed language with capabilities of garbage collection for better memory performance. It supports multiple programming paradigms, including structured, object-oriented, and functional programming.
Dynamic typing in Python allows you to determine the type of a variable at runtime rather than during code compilation.
Example:
x = 5 # 'x' is an integer
x = "Hello" # Now, 'x' is a string
Here, x can hold different types of data (first an integer, then a string) during its lifecycle. Python internally tracks the type of x and adjusts its behavior based on the current value.
32. What are loops in Python? How do you write a nested for-loop program?
The loop is a sequence of instructions that gets executed repeatedly until and unless an exit condition is reached.
There are two types of loops in Python:
- For Loop: This Loop iterates over a sequence like lists, strings, tuples or any other iterable object and is used when the number of iterations is known in advance.
Example:
for i in range(5):
print(i)
Output:
0 1 2 3 4
- While Loop: A while loop continues executing as long as the specified condition is true. It’s useful when the number of iterations is not known in advance.
Example:
count = 0
while count < 5:
print(count)
count += 1
Output:
0 1 2 3 4
- Nested For-Loop in Python: A nested for-loop is a loop inside another loop. It becomes useful when you need to iterate over multiple dimensions, like rows and columns of a matrix.
Example:
for i in range(3): # Outer loop (runs 3 times)
for j in range(2): # Inner loop (runs 2 times for each outer loop iteration)
print(f"i = {i}, j = {j}")
Output:
i = 0, j = 0i = 0, j = 1i = 1, j = 0i = 1, j = 1i = 2, j = 0i = 2, j = 1
33. What are collections? What is the significance of collections in Python?
Collections refer to data structures or containers capable of holding collective data in a single variable. These data structures are alternatives to built-in types such as lists, dictionaries, sets, and tuples
Let’s take an example to understand it. Suppose you have lots of books and are trying to build a library. Each book is different; some are about life lessons, some are about stories, and some are about magic. In Python, collections are like those collections of books. They help you organize lots of things (like numbers, words, or other data) in an organized way, just like how you organize your books in your library.
Collection Module implements specialized container data types, providing alternatives to Python’s general-purpose built-in containers.
- namedtuple: A tuple subclass that allows accessing elements by name and index. It provides a more readable and self-documenting structure.
- deque: A deque or double-ended queue allows efficiently adding and removing elements from both ends, which is useful for implementing queues and stacks.
- Counter: A dictionary subclass for counting hashable objects, which is used to count occurrences of elements in a collection like a list or string.
- defaultdict: It is a dictionary subclass that provides a default value for a nonexistent key. This is useful when you want to avoid KeyError and automatically initialize missing keys.
- OrderedDict: A dictionary subclass that maintains the order of keys as they are added. In Python 3.7+, regular dictionaries maintain insertion order by default, but OrderedDict ensures this behavior in earlier versions and provides extra methods.
- ChainMap: A class that groups multiple dictionaries or mappings into a single view
34. What is the difference between %, /, //?
In Python, %, /, and // are arithmetic operators with distinct functions:
- The ‘ % ’ is the modulo operator, which returns the remainder of a division. For instance, 5 % 2 would return 1.
- The ‘ / ’ is the division operator that performs floating-point division and returns a float. For example, 5 / 2 would return 2.5.
- The ‘ // ’ is the floor division operator that performs division but rounds down the result to the nearest whole number. So 5 // 2 would return 2.
35. What is the method to write comments in Python?
Python comments are statements used by the programmer to increase the readability of the code. With the help of the #, you can define a single comment. Another way of commenting is to use the docstrings (strings enclosed within triple quotes).
Example:
#Comments in Python
print("Comments in Python ")
Output:
Comments in Python
36. Do we need to declare variables with respective data types in Python?
No, Python is a dynamically typed language, and Interpreter automatically identifies the data-type of a variable based on the type of value assigned.
37. What distinguishes lists from tuples?
Here are the major differences between List and Tuples:
Lists |
Tuples |
Lists are mutable, i.e., they can be edited |
Tuples possess immutability, denoting their incapability of being modified like lists. |
Lists are usually slower than tuples |
Tuples are faster than lists |
Lists consume a lot of memory |
Tuples consume less memory comparatively |
Lists have a higher likelihood of experiencing unexpected changes, making them less reliable in terms of errors |
Tuples offer increased reliability due to their resistance to unexpected modifications |
38. Is this statement true: “Python is a case-sensitive language”?
Yes, Python is a case-sensitive language. It is important to note that “Function” and “function” are distinct entities, similar to how SQL and Pascal handle them differently.
39. What is the method for generating random numbers in Python?
Random Module is used to generate a random number
Example:
import random
random_integer = random.randint(1, 100)
# Generate a random integer between 1 and 100
print(random_integer)
Output:
4
40. What does len() do?
Len() function is a builtin method that is used to get the length of the sequences like list, string, and array
41. What is file handling in Python? What are the various file-handling operations in Python?
File handling is a technique that handles file operations such as the process of opening, reading, writing, and manipulating files on the file system.
Python File Handling Operations can be categorized into the following categories:
- ‘r’: Read (default mode).
- ‘w’: Write (creates a new file or truncates an existing file).
- ‘a’: Append (adds content to the end of an existing file).
- ‘b’: Binary mode (used for binary files).
42. What is PEP 8?
PEP in Python stands for Python Enhancement Proposal. It comprises a collection of guidelines that outline the optimal approach for crafting and structuring Python code to improve the readability and clarity of the code.
43. What is PYTHONPATH?
PYTHONPATH is an environment variable in Python that specifies a list of directories where the Python interpreter looks for modules and packages to import. By default, Python searches for modules in the current directory and the standard library directories, but you can extend this search path using the PYTHONPATH variable.
44. What are Python namespaces?
It ensures the names assigned to objects within a program are unique and can be used without conflict. In Python, namespaces has a unique name for each object in Python.
Let’s examine some examples of namespaces:
- The Local Namespace is specific to a function and contains the names defined within that function. It is created temporarily when the function is called and is cleared once the function finishes executing.
- The Global Namespace includes names from imported modules or packages that are used in the current project. It is created when the package is imported into the script and remains accessible throughout the script’s execution.
- The Built-in Namespace comprises the built-in functions provided by Python’s core, as well as specific names dedicated to various types of exceptions.
Example:
x = 10 # Global namespace
def outer_function():
x = 20 # Enclosing namespace
def inner_function():
x = 30 # Local namespace
print("Inner x:", x) # Output: 30
inner_function()
print("Outer x:", x) # Output: 20
outer_function()
print("Global x:", x) # Output: 10
Output:
Inner x: 30
Outer x: 20
Global x: 10
45. Explain the difference between pickling and unpickling.
Here’s a comparison of pickling and unpickling in table format:
Aspect |
Pickling |
Unpickling |
Definition |
The process of converting a Python object into a byte stream. |
The reverse process of converting a byte stream back into the original Python object. |
Purpose |
To save the state of an object for storage or transmission. |
To retrieve and reconstruct the original object from its serialized format. |
Usage |
– pickle.dump(obj, file) writes an object to a file.
– pickle.dumps(obj) returns a byte stream. |
– pickle.load(file) reads an object from a file.
– pickle.loads(byte_stream) reconstructs an object from a byte stream. |
Example Function |
pickle.dump(data, file) |
loaded_data = pickle.load(file) |
46. What do you understand about iterators in Python?
iterators are objects that allow us to traverse through a collection (such as lists, tuples, dictionaries, or sets). They use the __iter__() and __next__() methods to retrieve the next element until there are no more. Iterators are commonly used in for loops and can be created for custom objects. They promote efficient memory usage and enable lazy evaluation of elements.
47. What is Experimental Just-in-Time (JIT) Compilation in Python
Experimental Just-in-Time (JIT) Compilation in support in Python 3.14 with CPython as the main interpreter. which is known as an upcoming performance enhancement feature introduced. The goal of JIT is to improve the execution speed of Python code by compiling parts of it during runtime instead of interpreting it line-by-line, as is the case traditionally.
48. Can we use else with For in Python?
Yes, The else clause in a for loop is executed when the loop completes normally.
Example:
for i in range(5):
print(i)
else:
print("Loop completed successfully.")
Output:
0 1 2 3 4 Loop completed successfully
Python Advanced Interview Question
49. What is the purpose of using super() in Python classes?
The super() function in Python is used to call methods from a parent within a subclass.
This method is also known as method overriding.
Example:
Python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def get_details(self):
return f"Name: {self.name}, Age: {self.age}"
class Employee(Person):
def __init__(self, name, age, id):
super().__init__(name, age)
self.id = id
def get_details(self):
return f"Name: {self.name}, Age: {self.age}, ID: {self.id}"
emp = Employee("John Doe", 30, 1234)
print(emp.get_details())
Output:
Name: John Doe, Age: 30, ID: 1234
50. Explain the use of yield in Python with an example.
The yield keyword is used to create a generator function which is used to return a list of values from a function.
Example:
def countdown(n):
while n > 0:
yield n # Yield the current value of n
n -= 1 # Decrement n
# Using the generator
for number in countdown(5):
print(number)
Output:
5, 4, 3, 2, 1
51. What is multi-threading in Python?
Multithreading is a technique where processors execute multiple threads concurrently within a single process. A thread is the smallest unit of a CPU’s execution that can run independently. By using multiple threads, a program can perform several tasks simultaneously, which can improve performance, particularly for I/O-bound tasks.
Example:
import threading
import time
# Function to be executed in a thread
def print_numbers():
for i in range(5):
print(f"Number: {i}")
time.sleep(1) # Simulate a delay
# Function to be executed in a thread
def print_letters():
for letter in 'ABCDE':
print(f"Letter: {letter}")
time.sleep(1) # Simulate a delay
# Creating threads
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
# Starting threads
thread1.start()
thread2.start()
# Waiting for threads to complete
thread1.join()
thread2.join()
print("Done!")
Output:
Number: 0
Letter: A
Number: 1
Letter: B
Number: 2
Letter: C
Number: 3
Letter: D
Number: 4
Letter: E
Done!
Number: 0
Letter: A
Number: 1
Letter: B
Number: 2
Letter: C
Number: 3
Letter: D
Number: 4
Letter: E
Done
52. What are Access Specifiers in Python?
Access specifiers (also known as access modifiers) are used to control the visibility or accessibility of class attributes and methods.
- Public members: Can be accessed from anywhere.
- Protected members: Signaled by a single underscore _, indicating they should only be accessed within the class or subclasses.
- Private members: Indicated by a double underscore __, which makes the member less accessible outside the class by using name mangling.
53. Does Python support multiple inheritance?
Yes, Python supports multiple inheritance, which means a class can inherit from more than one parent class. In multiple inheritance, a class can have multiple base classes, and it inherits attributes and methods from all of them.
Syntax:
Class Base1:
Body of the class
Class Base2:
Body of the class
Class Derived(Base1, Base2):
Body of the class
54. Does Python support Switch Case?
No, Python does not have a built-in switch statement like some other languages (such as C or Java). Instead, Python developers typically use Match and Case, if-elif-else chains, or dictionary mappings to achieve similar functionality.
55. What is Walrus Operator?
The Walrus Operator (:=) is a new feature introduced in Python 3.8. It allows you to assign a value to a variable and return the value within a single expression. This is known as assignment expression
Example:
numbers = [1, 2, 3, 4, 5]
while (n := len(numbers)) > 0:
print(numbers.pop())
Output:
5 4 3 2 1
Python OOPS Interview Questions & Answers
56. What are the four pillars of OOP? Explain each
Here are the main four pillars of OOPs:
- Inheritance: Inheritance allows us to inherit the behaviors or properties from the parent class to the child class.
- Polymorphism: Polymorphism means “many forms” and in programming functions with the same name that can be executed on many objects or classes for different behavior.
- Encapsulation: Encapsulation is the practice of bundling the data (attributes) and methods (functions) that operate on the data into a single unit (class) and restricting direct access to some of the object’s components.
- Abstraction: Abstraction is the process of hiding implementation details and showing only essential features of an object.
57. What is a class and an object in Python
A class is a blueprint for creating objects. It contains member functions, attributes, etc., that get instantiated when the object is called.
On the other hand, an object is nothing but an instance of a class, possessing state, identity, and functionality, and is used to call class members.
Let’s take a look at a simple example:
Here, we will create a class named Office using Python
Example:
class Office:
def __init__(self):
print("class is created")
def sample(self):
self.employee = "ramesh"
print(self.employee)
# Now we will create an object for the class Office.
#Object is created
obj = Office()
#using object to call member functions and their attributes
obj.sample()
Output:
class is created
ramesh
58. What are constructors?
Constructors are called when an object is created for a class. Constructors are used to instantiate the objects and assign values to them.
Example:
class Office:
def __init__(self):
print("class is created")
#Object is created
obj = Office()
Output:
class is created
59. What is abstraction?
One of the pillars of object-oriented programming is abstraction. Abstraction is a very simple process where only the necessary details are shown, and the background computations or processes stay hidden. To simplify, let’s try to understand abstraction with an example:
Let’s say you visit a motor showroom to buy your new car. The dealer will take you for a quick ride to show you the features of the car.
The noticeable thing here is that you will be shown the entire car, but you will not be able to figure out how the actual combustion and other necessary details to move the car are working. This is exactly how abstraction works: only the necessary details are shown, and internal functionality is hidden from the users.
Advanced Python Technical Coding Questions
60. Write a program in Python to find the largest and second-largest element in a list using Python.
Here the problem statement says that we have to find out the largest and second-largest element from a list containing.
def find_largest_and_second_largest(numbers):
if len(numbers) < 2: return "List must contain at least two elements."
# Initialize the largest and second largest elements
largest = second_largest = float('-inf') for num in numbers:
if num > largest:
second_largest = largest
largest = num
elif num > second_largest and num != largest:
second_largest = num
if second_largest == float('-inf'):
return "There is no second largest element."
return largest, second_largest
# Example usage
numbers = [12, 35, 1, 10, 34, 1]
result = find_largest_and_second_largest(numbers)
print(f"Largest element: {result[0]}, Second largest element: {result[1]}")
Output:
Largest element: 35, Second largest element: 34
61. Write a program in Python to produce a Star triangle
The below code produces a star triangle-
def Star_triangle(n):
for x in range(n):
print(' '*(n-x-1)+'*'*(2*x+1))
Star_triangle(9)
Output:
*
***
*****
*******
*********
***********
*************
***************
*****************
62. Write a program to produce the Fibonacci series in Python
The Fibonacci series refers to a series where an element is the sum of two elements before it.
Example:
n = 10
num1 = 0
num2 = 1
next_number = num2
count = 1
while count <= n:
print(next_number, end=" ")
count += 1
num1, num2 = num2, next_number
next_number = num1 + num2
print()
Output:
1 2 3 5 8 13 21 34 55 89
63. Write a program in Python to check if a number is prime
The below code is used to check if a number is prime or not
num = 13
if num > 1:
for i in range(2, int(num/2)+1):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
Output:
13 is a prime number
64. Write a program to check even odd numbers using shorthand if-else statements.
Let’s first understand even and odd numbers. When can a number be even? A number is even when divided by two and returns a remainder zero. Now we know that the remainder can be determined with the help of the modulus function (%), which returns the remainder of the division. Now, let’s go ahead and write the program.
# Defining the Function
def EvenOdd(n):
print("Even Number") if(n%2 == 0) else print("Odd Number")
# Calling the Function:
EvenOdd(21) # Output: Odd Number
EvenOdd(12) # Output: Even Number
Output:
Odd Number
Even Number
65. Write a Python program to count the total number of lines in a text file.
This Python program defines a function to count lines in a text file. It opens the file, uses a generator expression to count lines efficiently, and handles errors for missing files. The function returns the total line count, and an example usage demonstrates how to call it with a file path.
def file_count(fname):
with open(fname) as f:
for i, _ in enumerate(f):
pass
return i + 1
print("Total number of lines in the text file:",
file_count("file.txt"))
66. Write a program in Python to execute the Bubble sort algorithm.
def bubble_sort(arr):
# Outer loop to iterate through the list n times
for n in range(len(arr) - 1, 0, -1):
# Inner loop to compare adjacent elements
for i in range(n):
if arr[i] > arr[i + 1]:
# Swap elements if they are in the wrong order
swapped = True
arr[i], arr[i + 1] = arr[i + 1], arr[i]
# Sample list to be sorted
arr = [39, 12, 18, 85, 72, 10, 2, 18]
print("Unsorted list is:")
print(arr)
bubble_sort(arr)
print("Sorted list is:")
print(arr)
Output:
Unsorted list is:
[39, 12, 18, 85, 72, 10, 2, 18]
Sorted list is:
[2, 10, 12, 18, 18, 39, 72, 85]
Explanation – Refer to another Publish article
67. What is monkey patching in Python?
Monkey patching is the term used to denote modifications that are done to a class or a module during runtime. This can only be done as Python supports changes in the behavior of the program while it is being executed.
The following is an example, denoting monkey patching in Python:
# monk.py
class A:
def func(self):
print ("func() is being called")
The above module (monk) is used to change the behavior of a function at runtime as shown below:
import monk
def monkey_f(self):
print ("monkey_f() is being called")
# replacing address of "func" with "monkey_f"
monk.A.func = monkey_f
obj = monk.A()
# calling function "func" whose address got replaced
# with function "monkey_f()"
obj.func()
Output:
monkey_f() is being called
68. Write a Program to print the ASCII Value of a character in Python.
We can can print the ASCII value of a character in Python using the built-in ord() function.
x= 'a'
# print the ASCII value of the assigned character stored in x
print(" ASCII value of '" + x + "' is", ord(x))
Output:
65
69. How will you reverse a list in Python?
There is multiple methods:
- Using reverse() method
- Using slicing technique
- Using reversed() function
- reversed() function
# Example using a loop
my_list = [1, 2, 3, 4, 5]
reversed_list = []
for item in my_list:
reversed_list.insert(0, item)
print(reversed_list) #
Output:
[5, 4, 3, 2, 1]
70. Write a program to Reverse a list using Enumerate in Python.
Reverse a list using the enumerate() function in Python by iterating over the original list and creating a new list with the elements in reverse order.
# Function to reverse a list using enumerate
def reverse_list(original_list):
reversed_list = []
# Using enumerate to iterate through the original list
for index, value in enumerate(original_list):
reversed_list.insert(0, value)
# Insert elements at the beginning of the new list
return reversed_list
# Example usage
my_list = [1, 2, 3, 4, 5]
reversed_list = reverse_list(my_list)
print("Original List:", my_list)
print("Reversed List:", reversed_list)
Output:
Original List: [1, 2, 3, 4, 5]
Reversed List: [5, 4, 3, 2, 1]
71. How will you remove the last object from a list in Python?
The pop() function removes the last object (obj) from the list.
my_list = [1, 2, 3, 4, 5]
my_list.pop()
72. Write a Python program to print a list of primes in a given range.
In this program where we need to check if the number is a prime number or not, we are making use of a very simple approach. Firstly we need to understand what is a Prime Number. A whole number greater than 1 cannot be exactly divided by any whole number other than itself and 1.
Let’s formulate the approach:
- Check if the number is greater or less than 1. If less than one returns that it is not a prime number immediately as the definition says “A Whole number greater than 1”
- If not less than one, check if the number has some other factors or not. If it has returned that it is not a prime number.
- Lastly, if it passes all the tests returns that it is a prime number.
Now let’s have a look at the program to check if the number is a prime number or not.
# Defining a Function
def isPrime(num):
# Checking if num > 1 because there are no prime numbers less than 1
if(num > 1):
# Looping through the elements in a range of 2,num to find factors
for i in range(2,num):
# if three is a factor other than 1
if(num % i == 0):
# Return Fales in Flag i.e not a prime number
flag = False
# End the Loop
break
else:
# If there is no factor other than 1 return True in Flag
flag = True
else:
# IF the number is less than 1, return False in Flag
flag = False
# Finally return the Final value of the flag
return flag
# Sample input
num = 5
# Check if the flag is True or False
if (isPrime(num)):
# If Flag is True print
print("It is a Prime Number")
else:
# If Flag is False print
print("It is a not a Prime Number")
73. Write a Python program to check whether the given input is an Armstrong number.
def armstrong(num):
sum = 0
temp = num
while temp > 0:
x = temp % 10
sum = sum + x**3
temp = temp // 10
print("armstrong") if sum == num else print("not an armstrong")
armstrong(153)
Output:
Armstrong
74. Write a program to find the greatest of the two numbers.
num1 = 100
num2 = 200
if num1 > num2:
print(f"{num1} is greater than {num2}")
else:
print(f"{num2} is greater than {num1}")
Output:
200 is greater than 100
75. Write a Python program to check whether a given string is a palindrome without using an iterative method.
A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam.
def fun(string):
s1 = string
s = string[::-1]
if s1 == s:
return True
else:
return False
print(fun("madam"))
Output:
True
76. What is the easiest way to calculate percentiles when using Python?
The easiest and most efficient way to calculate percentiles in Python is to use NumPy arrays and their functions.
import numpy as np
a = np.array([1,2,3,4,5,6,7])
p = np.percentile(a, 50) #Returns the 50th percentile, which is also the median
print(p)
Output:
4.0
77. Write a Python program that removes duplicates from a list
Removing duplicates from a list can be done easily by converting the list into a set and then moving it back to a list. As it is a property of a set that can only contain unique.
# Sample Data in List
Sample = [1,1,0,0,1,0,2,0,3,2,2,4,4,2,3]
# Converting the list to set to remove duplicates
SetSample = set(Sample)
# Converting the set to a list again
ListSample = list(SetSample)
# Printing the Output
print(ListSample)
Output:
[0, 1, 2, 3, 4]
78. Write a Python program that will reverse a string without using the slicing operation or reverse() function.
# Defining the function
def reverseString(x):
# Declaring an empty String
NewString = ""
# Traversing through individual characters in a string
for i in x:
# Add the character to the empty string
NewString = i + NewString
# return the new string
return NewString
# Sample String
string = "Intellipaat"
# Function Call
ReversedString = reverseString(string)
# Printing Output
print(ReversedString)
Output:
taapilletnI