fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)
['apple', 'cherry']
#48. Remove an Item with
.pop()Remove an item at a specific index (or the last item if no index is given).
fruits = ["apple", "banana", "cherry"]
fruits.pop(1)
print(fruits)
['apple', 'cherry']
#49. Get List Length
Use
len() to get the number of items.numbers = [10, 20, 30, 40]
print(len(numbers))
4
#50. Slicing a List
Get a range of items from a list.
numbers = [0, 1, 2, 3, 4, 5, 6]
print(numbers[2:5]) # Items from index 2 to 4
[2, 3, 4]
#51. Check if an Item Exists
Use the
in keyword.fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Yes, banana is in the list.")
Yes, banana is in the list.
#52. Sort a List with
.sort()Sorts the list in place (modifies the original list).
numbers = [3, 1, 4, 1, 5, 9]
numbers.sort()
print(numbers)
[1, 1, 3, 4, 5, 9]
#53. Copy a List
Use the
.copy() method to avoid modifying the original.original = [1, 2, 3]
copied = original.copy()
copied.append(4)
print(f"Original: {original}")
print(f"Copied: {copied}")
Original: [1, 2, 3]
Copied: [1, 2, 3, 4]
#54. Join Two Lists
Combine two lists using the
+ operator.list1 = ["a", "b"]
list2 = [1, 2]
list3 = list1 + list2
print(list3)
['a', 'b', 1, 2]
#55. List of Lists (2D List)
A list that contains other lists.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][1]) # Get the item at row 1, column 1
5
---
Part 6: Dictionaries, Tuples, Sets (Examples 56-70)
#56. Create a Dictionary
An unordered collection of key-value pairs.
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print(person){'name': 'Alice', 'age': 25, 'city': 'New York'}#57. Access Dictionary Values
Use the key in square brackets.
person = {"name": "Alice", "age": 25}
print(person["name"])Alice
#58. Add or Change a Dictionary Item
Assign a value to a key.
person = {"name": "Alice", "age": 25}
person["age"] = 26 # Change value
person["country"] = "USA" # Add new item
print(person){'name': 'Alice', 'age': 26, 'country': 'USA'}#59. Get Dictionary Keys
Use the
.keys() method.person = {"name": "Alice", "age": 25}
print(person.keys())dict_keys(['name', 'age'])
#60. Get Dictionary Values
Use the
.values() method.person = {"name": "Alice", "age": 25}
print(person.values())dict_values(['Alice', 25])
#61. Loop Through a Dictionary
Iterate over the keys.
person = {"name": "Alice", "age": 25}
for key in person:
print(f"{key}: {person[key]}")name: Alice
age: 25
#62. Loop Through Dictionary Items
Use
.items() to get both keys and values.❤1
person = {"name": "Alice", "age": 25}
for key, value in person.items():
print(f"{key} -> {value}")name -> Alice
age -> 25
#63. Check if a Key Exists
Use the
in keyword.person = {"name": "Alice", "age": 25}
if "age" in person:
print("Age key exists.")Age key exists.
#64. Create a Tuple
A tuple is an ordered collection that is unchangeable (immutable).
coordinates = (10, 20)
print(coordinates)
(10, 20)
#65. Access Tuple Items
Same as lists, using index.
coordinates = (10, 20, 30)
print(coordinates[0])
10
#66. Tuple Immutability
You cannot change a tuple's items after it is created.
# This code will produce an error
coordinates = (10, 20)
# coordinates[0] = 5 # This would raise a TypeError
print("Tuples cannot be changed.")
Tuples cannot be changed.
#67. Create a Set
A set is an unordered collection with no duplicate items.
numbers = {1, 2, 3, 2, 4} # The duplicate '2' is ignored
print(numbers){1, 2, 3, 4}#68. Add Item to a Set
Use the
.add() method.fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits){'banana', 'apple', 'cherry'}
(Note: Order is not guaranteed)#69. Set Union
Combine two sets using
| or .union().set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2){1, 2, 3, 4, 5}#70. Set Intersection
Get items that are in both sets using
& or .intersection().set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 & set2){3}---
Part 7: Functions (Examples 71-80)
#71. Define a Simple Function
Use the
def keyword to create a function.def greet():
print("Hello from a function!")
greet() # Call the function
Hello from a function!
#72. Function with a Parameter
Pass information into a function.
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
greet("Bob")
Hello, Alice!
Hello, Bob!
#73. Function with Multiple Parameters
def add_numbers(x, y):
print(x + y)
add_numbers(5, 3)
8
#74. Function with a
return ValueReturn a value from a function to be used elsewhere.
def multiply(x, y):
return x * y
result = multiply(4, 5)
print(result)
20
#75. Function with a Default Parameter Value
def greet(name="World"):
print(f"Hello, {name}!")
greet()
greet("Python")
Hello, World!
Hello, Python!
#76. Keyword Arguments
Call a function by specifying the parameter names.
def show_info(name, age):
print(f"Name: {name}, Age: {age}")
show_info(age=30, name="Charlie")
Name: Charlie, Age: 30
#77. A Function that Returns a Boolean
def is_even(number):
return number % 2 == 0
print(is_even(10))
print(is_even(7))
True
False
#78. Arbitrary Arguments (
*args)Allow a function to accept a variable number of arguments.
def sum_all(*numbers):
total = 0
for num in numbers:
total += num
return total
print(sum_all(1, 2, 3, 4))
10
#79. Lambda Function (Anonymous Function)
A small, one-line function.
# A lambda function that adds 10 to the number passed in
x = lambda a : a + 10
print(x(5))
15
#80. Scope (Local vs. Global Variables)
A variable created inside a function is only available inside that function.
def my_function():
local_var = "I am local"
print(local_var)
my_function()
# print(local_var) # This would cause a NameError
I am local
---
Part 8: Modules & File I/O (Examples 81-90)
#81. Import a Module
Use code from another file or library.
import math
print(math.sqrt(16))
4.0
#82. Import a Specific Function
Use
from ... import ... to import only what you need.from datetime import date
today = date.today()
print(today)
(Current date will be printed, e.g., 2023-10-27)
#83. The
random ModuleGenerate random numbers.
import random
# Random integer between 1 and 10 (inclusive)
print(random.randint(1, 10))
(A random number between 1 and 10, e.g., 7)
#84. Write to a Text File (
w)Create a new file and write content to it. Overwrites existing files.
# This creates a file named "greeting.txt"
with open("greeting.txt", "w") as file:
file.write("Hello, File!")
print("File written successfully.")
File written successfully.
#85. Read from a Text File (
r)Open a file and read its contents.
# Assumes "greeting.txt" from the previous example exists
with open("greeting.txt", "r") as file:
content = file.read()
print(content)
Hello, File!
#86. Append to a Text File (
a)Add content to the end of an existing file.
with open("greeting.txt", "a") as file:
file.write("\nHave a nice day.")
print("File appended successfully.")File appended successfully.
#87. Reading a File Line by Line
# Assumes "greeting.txt" now has two lines
with open("greeting.txt", "r") as file:
for line in file:
print(line.strip()) # .strip() removes newline characters
Hello, File!
Have a nice day.
#88. Create a Class (OOP Basics)
A blueprint for creating objects.
class Dog:
def bark(self):
print("Woof!")
my_dog = Dog() # Create an object (instance) of the Dog class
my_dog.bark()
Woof!
#89. The
__init__() Method (Constructor)A special method that runs when an object is created.
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} says Woof!")
dog1 = Dog("Rex")
dog1.speak()
Rex says Woof!
#90. Class Inheritance
Create a new class that inherits properties from an existing class.
class Animal:
def speak(self):
print("Animal speaks")
class Cat(Animal): # Cat inherits from Animal
def speak(self): # Override the method
print("Meow")
my_cat = Cat()
my_cat.speak()
Meow
---
Part 9: Error Handling & Advanced Topics (Examples 91-100)
#91.
try...except BlockHandle errors gracefully without crashing the program.
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
Error: Cannot divide by zero.
#92. Handling
ValueErrortry:
number = int("abc")
except ValueError:
print("Invalid number format.")
Invalid number format.
❤1
#93. The
The
#94. List Comprehension
A concise way to create lists.
#95. List Comprehension with a Condition
#96. Dictionary Comprehension
A concise way to create dictionaries.
#97. The
Get both the index and the value when looping.
#98. The
Combine two lists element-wise.
#99.
#100. A Simple Command-Line App
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
finally ClauseThe
finally block executes regardless of whether an error occurred.try:
print("Hello")
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Hello
The 'try except' is finished
#94. List Comprehension
A concise way to create lists.
# Create a list of squares for numbers 0 through 9
squares = [x**2 for x in range(10)]
print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#95. List Comprehension with a Condition
# Create a list of even numbers from 0 to 19
evens = [x for x in range(20) if x % 2 == 0]
print(evens)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
#96. Dictionary Comprehension
A concise way to create dictionaries.
# Create a dictionary of numbers and their squares
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}#97. The
enumerate() FunctionGet both the index and the value when looping.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
0 apple
1 banana
2 cherry
#98. The
zip() FunctionCombine two lists element-wise.
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")
Alice is 25 years old.
Bob is 30 years old.
Charlie is 35 years old.
#99.
*args and **kwargs in a Function Definition*args for non-keyword arguments, **kwargs for keyword arguments.def my_func(*args, **kwargs):
print("Args:", args)
print("Kwargs:", kwargs)
my_func(1, 2, 3, name="Alice", city="New York")
Args: (1, 2, 3)
Kwargs: {'name': 'Alice', 'city': 'New York'}
#100. A Simple Command-Line App
import sys
# To run: python your_script_name.py YourName
# The output is simulated.
# name = sys.argv[1] # Gets the first argument after the script name
name = "World" # Simulating for demonstration
print(f"Hello, {name}!")
Hello, World!
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❤2
Top 100 Python Interview Questions & Answers
#Python #InterviewQuestions #CodingInterview #Programming #PythonDeveloper
👇 👇 👇 👇
#Python #InterviewQuestions #CodingInterview #Programming #PythonDeveloper
Please open Telegram to view this post
VIEW IN TELEGRAM
❤1
Top 100 Python Interview Questions & Answers
#Python #InterviewQuestions #CodingInterview #Programming #PythonDeveloper
Part 1: Core Python Fundamentals (Q1-20)
#1. Is Python a compiled or an interpreted language?
A: Python is an interpreted language. The Python interpreter reads and executes the source code line by line, without requiring a separate compilation step. This makes development faster but can result in slower execution compared to compiled languages like C++.
#2. What is the GIL (Global Interpreter Lock)?
A: The GIL is a mutex (a lock) that allows only one thread to execute Python bytecode at a time within a single process. This means even on a multi-core processor, a single Python process cannot run threads in parallel. It simplifies memory management but is a performance bottleneck for CPU-bound multithreaded programs.
#3. What is the difference between Python 2 and Python 3?
A: Key differences include:
•
• Integer Division: In Python 2,
• Unicode: In Python 3, strings are Unicode (UTF-8) by default. In Python 2, you had to explicitly use
#4. What are mutable and immutable data types in Python?
A:
• Mutable: Objects whose state or contents can be changed after creation. Examples:
• Immutable: Objects whose state cannot be changed after creation. Examples:
#5. How is memory managed in Python?
A: Python uses a private heap to manage memory. A built-in garbage collector automatically reclaims memory from objects that are no longer in use. The primary mechanism is reference counting, where each object tracks the number of references to it. When the count drops to zero, the object is deallocated.
#6. What is the difference between
A:
•
•
#7. What is PEP 8?
A: PEP 8 (Python Enhancement Proposal 8) is the official style guide for Python code. It provides conventions for writing readable and consistent Python code, covering aspects like naming conventions, code layout, and comments.
#8. What is the difference between a
A:
•
•
#9. What are namespaces in Python?
A: A namespace is a system that ensures all names in a program are unique and can be used without conflict. It's a mapping from names to objects. Python has different namespaces: built-in, global, and local.
#Python #InterviewQuestions #CodingInterview #Programming #PythonDeveloper
Part 1: Core Python Fundamentals (Q1-20)
#1. Is Python a compiled or an interpreted language?
A: Python is an interpreted language. The Python interpreter reads and executes the source code line by line, without requiring a separate compilation step. This makes development faster but can result in slower execution compared to compiled languages like C++.
#2. What is the GIL (Global Interpreter Lock)?
A: The GIL is a mutex (a lock) that allows only one thread to execute Python bytecode at a time within a single process. This means even on a multi-core processor, a single Python process cannot run threads in parallel. It simplifies memory management but is a performance bottleneck for CPU-bound multithreaded programs.
#3. What is the difference between Python 2 and Python 3?
A: Key differences include:
•
print: In Python 2, print is a statement (print "hello"). In Python 3, it's a function (print("hello")).• Integer Division: In Python 2,
5 / 2 results in 2 (floor division). In Python 3, it results in 2.5 (true division).• Unicode: In Python 3, strings are Unicode (UTF-8) by default. In Python 2, you had to explicitly use
u"unicode string".#4. What are mutable and immutable data types in Python?
A:
• Mutable: Objects whose state or contents can be changed after creation. Examples:
list, dict, set.• Immutable: Objects whose state cannot be changed after creation. Examples:
int, float, str, tuple, frozenset.# Mutable example
my_list = [1, 2, 3]
my_list[0] = 99
print(my_list)
[99, 2, 3]
#5. How is memory managed in Python?
A: Python uses a private heap to manage memory. A built-in garbage collector automatically reclaims memory from objects that are no longer in use. The primary mechanism is reference counting, where each object tracks the number of references to it. When the count drops to zero, the object is deallocated.
#6. What is the difference between
is and ==?A:
•
== (Equality): Checks if the values of two operands are equal.•
is (Identity): Checks if two variables point to the exact same object in memory.list_a = [1, 2, 3]
list_b = [1, 2, 3]
list_c = list_a
print(list_a == list_b) # True, values are the same
print(list_a is list_b) # False, different objects in memory
print(list_a is list_c) # True, same object in memory
True
False
True
#7. What is PEP 8?
A: PEP 8 (Python Enhancement Proposal 8) is the official style guide for Python code. It provides conventions for writing readable and consistent Python code, covering aspects like naming conventions, code layout, and comments.
#8. What is the difference between a
.py and a .pyc file?A:
•
.py: This is the source code file you write.•
.pyc: This is the compiled bytecode. When you run a Python script, the interpreter compiles it into bytecode (a lower-level, platform-independent representation) and saves it as a .pyc file to speed up subsequent executions.#9. What are namespaces in Python?
A: A namespace is a system that ensures all names in a program are unique and can be used without conflict. It's a mapping from names to objects. Python has different namespaces: built-in, global, and local.
#10. Explain scope in Python.
A: Scope refers to the region of a program where a namespace is directly accessible. The scopes are searched in this order:
• Local: Inside the current function.
• Enclosing: In the enclosing functions (for nested functions).
• Global: At the top level of the module.
• Built-in: Names pre-assigned in Python (e.g.,
---
#11. What is the ternary operator in Python?
A: It's a concise way to write a simple if-else statement in a single line. The syntax is
#12. What are negative indexes?
A: Negative indexes are used to access elements from the end of a sequence (like a list or string).
#13. What is pickling and unpickling?
A: Pickling is the process of converting a Python object hierarchy into a byte stream (serialization). Unpickling is the inverse operation, converting a byte stream back into an object hierarchy (deserialization). The
#14. How do you copy an object in Python?
A:
• Shallow Copy: Creates a new object but inserts references to the objects found in the original.
• Deep Copy: Creates a new object and recursively copies all objects found in the original. Changes to the copied object will not affect the original. Use the
#15. What does the
A:
---
#16. What does
A: This is a common idiom in Python. The code inside this block will only run when the script is executed directly (not when it is imported as a module into another script). It's the entry point of the program.
#17. How do you concatenate strings in Python?
A:
• Use the
• Use an f-string (formatted string literal) for embedding expressions (most readable).
• Use the
A: Scope refers to the region of a program where a namespace is directly accessible. The scopes are searched in this order:
• Local: Inside the current function.
• Enclosing: In the enclosing functions (for nested functions).
• Global: At the top level of the module.
• Built-in: Names pre-assigned in Python (e.g.,
print, len). This is known as the LEGB rule.---
#11. What is the ternary operator in Python?
A: It's a concise way to write a simple if-else statement in a single line. The syntax is
[value_if_true] if [condition] else [value_if_false].age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
Adult
#12. What are negative indexes?
A: Negative indexes are used to access elements from the end of a sequence (like a list or string).
-1 refers to the last element, -2 to the second-to-last, and so on.my_list = ['a', 'b', 'c', 'd']
print(my_list[-1])
print(my_list[-2])
d
c
#13. What is pickling and unpickling?
A: Pickling is the process of converting a Python object hierarchy into a byte stream (serialization). Unpickling is the inverse operation, converting a byte stream back into an object hierarchy (deserialization). The
pickle module is used for this.import pickle
my_dict = {'name': 'Alice'}
# Pickling
with open('data.pkl', 'wb') as f:
pickle.dump(my_dict, f)
# Unpickling
with open('data.pkl', 'rb') as f:
loaded_dict = pickle.load(f)
print(loaded_dict)
{'name': 'Alice'}#14. How do you copy an object in Python?
A:
• Shallow Copy: Creates a new object but inserts references to the objects found in the original.
• Deep Copy: Creates a new object and recursively copies all objects found in the original. Changes to the copied object will not affect the original. Use the
copy module.import copy
original_list = [[1, 2], [3, 4]]
shallow = copy.copy(original_list)
deep = copy.deepcopy(original_list)
# Modify a nested object
shallow[0][0] = 99
print(f"Original: {original_list}") # Modified!
print(f"Shallow Copy: {shallow}")
print(f"Deep Copy: {deep}") # Not modified
Original: [[99, 2], [3, 4]]
Shallow Copy: [[99, 2], [3, 4]]
Deep Copy: [[1, 2], [3, 4]]
#15. What does the
pass statement do?A:
pass is a null statement. It's used as a placeholder where a statement is syntactically required but you don't want any code to execute. It's often used in empty functions or classes.def my_empty_function():
pass # No error, does nothing
my_empty_function()
print("Function executed.")
Function executed.
---
#16. What does
if __name__ == "__main__:" mean?A: This is a common idiom in Python. The code inside this block will only run when the script is executed directly (not when it is imported as a module into another script). It's the entry point of the program.
#17. How do you concatenate strings in Python?
A:
• Use the
+ operator for simple cases.• Use an f-string (formatted string literal) for embedding expressions (most readable).
• Use the
.join() method for concatenating a list of strings (most efficient).words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence)
Python is awesome
❤1
#18. What is type casting?
A: Type casting (or type conversion) is the process of converting a variable from one data type to another. Functions like
#19. What are Python literals?
A: A literal is a notation for representing a fixed value in source code. Examples include:
• String literals:
• Numeric literals:
• Boolean literals:
• Special literal:
#20. How do you create a multi-line string?
A: Use triple quotes, either
---
Part 2: Data Structures (Q21-40)
#21. What is the main difference between a List and a Tuple?
A: The primary difference is that Lists are mutable, meaning their elements can be changed, added, or removed. Tuples are immutable, meaning once they are created, their elements cannot be changed. Tuples are generally faster than lists.
#22. What are list comprehensions? Provide an example.
A: A list comprehension is a concise and readable way to create a list. It consists of brackets containing an expression followed by a
#23. How do you remove duplicates from a list?
A: The simplest way is to convert the list to a set and then back to a list. Sets automatically discard duplicate elements. This method does not preserve the original order.
#24. What is the difference between
A:
•
•
#25. Explain slicing in Python.
A: Slicing is a feature that allows you to access a range of elements from a sequence (like a list, string, or tuple). The syntax is
•
•
•
---
#26. Can a dictionary key be a list? Why or why not?
A: No. Dictionary keys must be of an immutable type. Since lists are mutable, they cannot be used as dictionary keys. You can use immutable types like strings, numbers, or tuples as keys.
A: Type casting (or type conversion) is the process of converting a variable from one data type to another. Functions like
int(), float(), str(), and list() are used for this.string_num = "123"
integer_num = int(string_num)
print(integer_num + 7)
130
#19. What are Python literals?
A: A literal is a notation for representing a fixed value in source code. Examples include:
• String literals:
"hello", 'world'• Numeric literals:
100, 3.14• Boolean literals:
True, False• Special literal:
None#20. How do you create a multi-line string?
A: Use triple quotes, either
""" or '''.multi_line = """This is a string
that spans across
multiple lines."""
print(multi_line)
This is a string
that spans across
multiple lines.
---
Part 2: Data Structures (Q21-40)
#21. What is the main difference between a List and a Tuple?
A: The primary difference is that Lists are mutable, meaning their elements can be changed, added, or removed. Tuples are immutable, meaning once they are created, their elements cannot be changed. Tuples are generally faster than lists.
#22. What are list comprehensions? Provide an example.
A: A list comprehension is a concise and readable way to create a list. It consists of brackets containing an expression followed by a
for clause, then zero or more for or if clauses.# Create a list of squares for numbers 0 through 9
squares = [x**2 for x in range(10)]
print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#23. How do you remove duplicates from a list?
A: The simplest way is to convert the list to a set and then back to a list. Sets automatically discard duplicate elements. This method does not preserve the original order.
my_list = [1, 2, 3, 2, 4, 1, 5]
unique_list = list(set(my_list))
print(unique_list)
[1, 2, 3, 4, 5]
#24. What is the difference between
.sort() and sorted()?A:
•
.sort() is a list method that sorts the list in-place (modifies the original list) and returns None.•
sorted() is a built-in function that takes an iterable as an argument and returns a new sorted list, leaving the original iterable unchanged.my_list = [3, 1, 2]
sorted_list = sorted(my_list)
print(f"Original list after sorted(): {my_list}")
print(f"New list from sorted(): {sorted_list}")
my_list.sort()
print(f"Original list after .sort(): {my_list}")
Original list after sorted(): [3, 1, 2]
New list from sorted(): [1, 2, 3]
Original list after .sort(): [1, 2, 3]
#25. Explain slicing in Python.
A: Slicing is a feature that allows you to access a range of elements from a sequence (like a list, string, or tuple). The syntax is
sequence[start:stop:step].•
start: The index of the first element to include.•
stop: The index of the first element to exclude.•
step: The amount to increment by.my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Elements from index 2 up to (not including) 5
print(my_list[2:5])
# Every second element
print(my_list[::2])
# Reverse the list
print(my_list[::-1])
[2, 3, 4]
[0, 2, 4, 6, 8]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
---
#26. Can a dictionary key be a list? Why or why not?
A: No. Dictionary keys must be of an immutable type. Since lists are mutable, they cannot be used as dictionary keys. You can use immutable types like strings, numbers, or tuples as keys.
#27. How do you merge two dictionaries?
A: In Python 3.9+, you can use the
#28. How do you iterate over the keys, values, and items of a dictionary?
A: Use the
#29. What is a set? What are its main properties?
A: A set is an unordered collection of unique elements.
• Unique: Sets cannot have duplicate members.
• Unordered: The elements are not stored in any specific order.
• Mutable: You can add or remove elements from a set.
#30. What is a
A: A
---
#31. How do you find the intersection of two sets?
A: Use the
#32. What is the difference between
A:
•
•
#33. How do you reverse a list?
A:
• Use the
• Use slicing
#34. What is
A:
#35. What is the time complexity of a key lookup in a list vs. a dictionary?
A:
• List: O(n), because in the worst case, you may have to scan the entire list to find an element.
• Dictionary/Set: O(1) on average. Dictionaries use a hash table, which allows for direct lookup of a key's location without scanning.
#36. How do you create an empty set?
A: You must use the
A: In Python 3.9+, you can use the
| (union) operator. For earlier versions, you can use the ** unpacking operator or the .update() method.dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# Using the | operator (Python 3.9+)
merged_dict = dict1 | dict2
print(merged_dict){'a': 1, 'b': 3, 'c': 4}#28. How do you iterate over the keys, values, and items of a dictionary?
A: Use the
.keys(), .values(), and .items() methods.my_dict = {'name': 'Alice', 'age': 25}
for key, value in my_dict.items():
print(f"{key}: {value}")name: Alice
age: 25
#29. What is a set? What are its main properties?
A: A set is an unordered collection of unique elements.
• Unique: Sets cannot have duplicate members.
• Unordered: The elements are not stored in any specific order.
• Mutable: You can add or remove elements from a set.
#30. What is a
frozenset?A: A
frozenset is an immutable version of a set. Once created, you cannot add or remove elements. Because they are immutable and hashable, they can be used as dictionary keys or as elements of another set.---
#31. How do you find the intersection of two sets?
A: Use the
& operator or the .intersection() method.set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 & set2){3, 4}#32. What is the difference between
.append() and .extend() for lists?A:
•
.append(element): Adds its argument as a single element to the end of a list.•
.extend(iterable): Iterates over its argument and adds each element to the list, extending the list.list_a = [1, 2, 3]
list_b = [1, 2, 3]
list_a.append([4, 5])
list_b.extend([4, 5])
print(f"After append: {list_a}")
print(f"After extend: {list_b}")
After append: [1, 2, 3, [4, 5]]
After extend: [1, 2, 3, 4, 5]
#33. How do you reverse a list?
A:
• Use the
.reverse() method to reverse the list in-place.• Use slicing
[::-1] to create a new, reversed copy of the list.my_list = [1, 2, 3, 4]
reversed_copy = my_list[::-1]
print(reversed_copy)
[4, 3, 2, 1]
#34. What is
defaultdict?A:
defaultdict is a subclass of the standard dict that is found in the collections module. It overrides one method and adds one writable instance variable. Its main advantage is that it does not raise a KeyError if you try to access a key that does not exist. Instead, it provides a default value for that key.from collections import defaultdict
d = defaultdict(int) # Default value for non-existent keys will be int(), which is 0
d['a'] += 1
print(d['a'])
print(d['b']) # Accessing a non-existent key
1
0
#35. What is the time complexity of a key lookup in a list vs. a dictionary?
A:
• List: O(n), because in the worst case, you may have to scan the entire list to find an element.
• Dictionary/Set: O(1) on average. Dictionaries use a hash table, which allows for direct lookup of a key's location without scanning.
#36. How do you create an empty set?
A: You must use the
set() constructor. Using {} creates an empty dictionary, not an empty set.empty_dict = {}
empty_set = set()
print(type(empty_dict))
print(type(empty_set))<class 'dict'>
<class 'set'>
❤1
#37. How can you get a value from a dictionary without raising a
A: Use the
#38. What is a hashable object?
A: An object is hashable if it has a hash value that never changes during its lifetime. This means it must be immutable. Hashable objects can be used as dictionary keys and set members. Examples:
#39. What is dictionary comprehension?
A: It is a concise and readable way to create a dictionary.
#40. Explain how to use
A: The
---
Part 3: Functions & Functional Programming (Q41-55)
#41. What are
A: They are used to pass a variable number of arguments to a function.
•
•
#42. What is a lambda function?
A: A lambda function is a small, anonymous function defined with the
#43. What is a decorator?
A: A decorator is a design pattern in Python that allows a user to add new functionality to an existing object (like a function) without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.
#44. What is a generator? What is the
A: A generator is a special type of iterator that is simpler to create. Instead of returning a value and terminating, a generator function uses the
KeyError?A: Use the
.get(key, default_value) method. It returns the value for the key if it exists, otherwise it returns the default_value (which is None if not specified).my_dict = {'a': 1}
print(my_dict.get('a'))
print(my_dict.get('b', 'Not Found'))1
Not Found
#38. What is a hashable object?
A: An object is hashable if it has a hash value that never changes during its lifetime. This means it must be immutable. Hashable objects can be used as dictionary keys and set members. Examples:
int, str, tuple.#39. What is dictionary comprehension?
A: It is a concise and readable way to create a dictionary.
# Create a dictionary of numbers and their squares
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}#40. Explain how to use
zip() to combine two lists.A: The
zip() function takes two or more iterables and returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument iterables. It stops when the shortest input iterable is exhausted.names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = list(zip(names, ages))
print(combined)
[('Alice', 25), ('Bob', 30), ('Charlie', 35)]---
Part 3: Functions & Functional Programming (Q41-55)
#41. What are
*args and **kwargs?A: They are used to pass a variable number of arguments to a function.
•
*args (Non-Keyword Arguments): Gathers extra positional arguments into a tuple.•
**kwargs (Keyword Arguments): Gathers extra keyword arguments into a dictionary.def my_func(a, b, *args, **kwargs):
print(f"a: {a}, b: {b}")
print(f"args: {args}")
print(f"kwargs: {kwargs}")
my_func(1, 2, 3, 4, name="Alice", city="NY")
a: 1, b: 2
args: (3, 4)
kwargs: {'name': 'Alice', 'city': 'NY'}
#42. What is a lambda function?
A: A lambda function is a small, anonymous function defined with the
lambda keyword. It can take any number of arguments but can only have one expression. They are often used when a simple function is needed for a short period.# A lambda function that doubles its input
double = lambda x: x * 2
print(double(5))
10
#43. What is a decorator?
A: A decorator is a design pattern in Python that allows a user to add new functionality to an existing object (like a function) without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.
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
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
#44. What is a generator? What is the
yield keyword?A: A generator is a special type of iterator that is simpler to create. Instead of returning a value and terminating, a generator function uses the
yield keyword. When yield is called, it "pauses" the function, returns the value, and saves its state. On the next call, it resumes execution from where it left off. Generators are memory efficient for working with large data sequences.def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
counter = count_up_to(3)
print(next(counter))
print(next(counter))
print(next(counter))
1
2
3
#45. What is the difference between an iterator and a generator?
A:
• Iterator: An object that implements the iterator protocol (
__iter__() and __next__() methods). It's more complex to create as you have to write a class.• Generator: A simpler way to create an iterator using a function with the
yield keyword. All generators are iterators, but not all iterators are generators.---
#46. Explain the
map() function.A: The
map(function, iterable) function applies the given function to every item of the iterable and returns a map object (an iterator) with the results.numbers = [1, 2, 3, 4]
squared_numbers = map(lambda x: x**2, numbers)
print(list(squared_numbers))
[1, 4, 9, 16]
#47. Explain the
filter() function.A: The
filter(function, iterable) function constructs an iterator from elements of the iterable for which the function returns True.numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))
[2, 4, 6]
#48. What does the
global keyword do?A: The
global keyword is used to modify a global variable from inside a function. Without it, assigning a value to a variable inside a function creates a new local variable.count = 0
def increment():
global count
count += 1
increment()
print(count)
1
#49. Can a function return multiple values?
A: Yes. A Python function can return multiple values by separating them with commas. Internally, Python packs these values into a single tuple and returns that tuple.
def get_name_and_age():
return "Alice", 25
name, age = get_name_and_age()
print(f"Name: {name}, Age: {age}")
Name: Alice, Age: 25
#50. What are docstrings?
A: A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. It is used to document what the code does. It is accessible via the
__doc__ attribute.def add(a, b):
"""This function adds two numbers and returns the result."""
return a + b
print(add.__doc__)
This function adds two numbers and returns the result.
---
#51. What are closures in Python?
A: A closure is a function object that remembers values in the enclosing scope even if they are not present in memory. It's a function that is defined inside another function (the enclosing function) and references variables from that enclosing function.
def outer_function(text):
def inner_function():
print(text) # inner_function "closes over" the text variable
return inner_function
my_func = outer_function("Hello")
my_func()
Hello
#52. What is recursion? Provide a simple example.
A: Recursion is a programming technique where a function calls itself in order to solve a problem. A recursive function must have a base case that stops the recursion.
# Calculate factorial using recursion
def factorial(n):
if n == 1:
return 1 # Base case
else:
return n * factorial(n - 1) # Recursive call
print(factorial(5))
120
#53. What is the difference between a function and a method?
A:
• A method is a function that "belongs to" an object. It is called on an object (
• A function is not associated with any object. It is called by its name (
#54. What does the
A: The
#55. What is a first-class function?
A: In Python, functions are "first-class citizens". This means they can be treated like any other object: they can be assigned to variables, stored in data structures (like lists), passed as arguments to other functions, and returned from functions.
---
Part 4: Object-Oriented Programming (OOP) (Q56-70)
#56. What are the four main principles of OOP?
A:
• Encapsulation: Bundling data (attributes) and methods that operate on the data into a single unit (a class).
• Inheritance: A mechanism where a new class (subclass) inherits attributes and methods from an existing class (superclass).
• Polymorphism: The ability of an object to take on many forms. For example, different classes can have methods with the same name that perform different actions.
• Abstraction: Hiding complex implementation details and showing only the essential features of the object.
#57. What is the difference between a class and an object?
A:
• A Class is a blueprint or template for creating objects. It defines a set of attributes and methods.
• An Object is an instance of a class. It is a concrete entity created from the class blueprint, with actual values for its attributes.
#58. What is
A:
#59. What is the
A:
#60. What is inheritance?
A: Inheritance allows us to define a class that inherits all the methods and properties from another class. The parent class is the class being inherited from, and the child class is the class that inherits.
---
#61. What is multiple inheritance?
A: Multiple inheritance is a feature where a class can inherit attributes and methods from more than one parent class. Python supports multiple inheritance.
A:
• A method is a function that "belongs to" an object. It is called on an object (
object.method()) and can access and modify the object's data (its attributes).• A function is not associated with any object. It is called by its name (
function()).#54. What does the
nonlocal keyword do?A: The
nonlocal keyword is used in nested functions to refer to a variable in the nearest enclosing scope (but not the global scope). It's used to modify variables in an outer (but not global) function.def outer():
x = "local"
def inner():
nonlocal x
x = "nonlocal"
print("inner:", x)
inner()
print("outer:", x)
outer()
inner: nonlocal
outer: nonlocal
#55. What is a first-class function?
A: In Python, functions are "first-class citizens". This means they can be treated like any other object: they can be assigned to variables, stored in data structures (like lists), passed as arguments to other functions, and returned from functions.
---
Part 4: Object-Oriented Programming (OOP) (Q56-70)
#56. What are the four main principles of OOP?
A:
• Encapsulation: Bundling data (attributes) and methods that operate on the data into a single unit (a class).
• Inheritance: A mechanism where a new class (subclass) inherits attributes and methods from an existing class (superclass).
• Polymorphism: The ability of an object to take on many forms. For example, different classes can have methods with the same name that perform different actions.
• Abstraction: Hiding complex implementation details and showing only the essential features of the object.
#57. What is the difference between a class and an object?
A:
• A Class is a blueprint or template for creating objects. It defines a set of attributes and methods.
• An Object is an instance of a class. It is a concrete entity created from the class blueprint, with actual values for its attributes.
#58. What is
self?A:
self represents the instance of the class. By using the self keyword, we can access the attributes and methods of the class in Python. It is the first argument passed to instance methods.#59. What is the
__init__ method?A:
__init__ is a special method in Python classes, also known as the constructor. It is automatically called when a new object of the class is created. It is used to initialize the object's attributes.class Dog:
def __init__(self, name):
self.name = name # Initialize the name attribute
print(f"{self.name} was born!")
my_dog = Dog("Rex")
Rex was born!
#60. What is inheritance?
A: Inheritance allows us to define a class that inherits all the methods and properties from another class. The parent class is the class being inherited from, and the child class is the class that inherits.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal): # Dog inherits from Animal
def bark(self):
print("Woof!")
d = Dog()
d.speak() # Inherited from Animal
d.bark()
Animal speaks
Woof!
---
#61. What is multiple inheritance?
A: Multiple inheritance is a feature where a class can inherit attributes and methods from more than one parent class. Python supports multiple inheritance.
class A:
def method(self):
print("Method from A")
class B:
def method(self):
print("Method from B")
class C(B, A): # Inherits from B, then A
pass
c = C()
c.method() # Calls method from B due to MRO
Method from B
#62. What is MRO (Method Resolution Order)?
A: MRO is the order in which Python looks for a method in a hierarchy of classes. In the case of multiple inheritance, it determines which parent class's method is called. You can view the MRO of a class using
#63. What is polymorphism?
A: Polymorphism means "many forms". In programming, it refers to methods/functions/operators with the same name that can be executed on many objects or classes.
#64. What is the difference between a class method and a static method?
A:
• Instance Method: Takes
•
•
#65. What is
A:
---
#66. What are public, protected, and private members?
A: These are conventions for encapsulation.
• Public: Accessible from anywhere. (e.g.,
• Protected: Conventionally treated as non-public; accessible within the class and its subclasses. Denoted by a single underscore prefix. (e.g.,
• Private: Accessible only from within the class. Python enforces this through name mangling. Denoted by a double underscore prefix. (e.g.,
#67. What is name mangling?
A: When an identifier starts with two underscores (like
#68. What are magic methods (or dunder methods)?
A: Magic methods are special methods with double underscores at the beginning and end of their names (e.g.,
#69. Explain the difference between
A:
•
•
A: MRO is the order in which Python looks for a method in a hierarchy of classes. In the case of multiple inheritance, it determines which parent class's method is called. You can view the MRO of a class using
ClassName.mro().#63. What is polymorphism?
A: Polymorphism means "many forms". In programming, it refers to methods/functions/operators with the same name that can be executed on many objects or classes.
class Cat:
def speak(self):
return "Meow"
class Dog:
def speak(self):
return "Woof"
def make_sound(animal):
print(animal.speak())
make_sound(Cat())
make_sound(Dog())
Meow
Woof
#64. What is the difference between a class method and a static method?
A:
• Instance Method: Takes
self as the first argument. It can access and modify instance attributes.•
@classmethod: Takes cls (the class itself) as the first argument. It can access and modify class attributes but not instance attributes. Often used as alternative constructors.•
@staticmethod: Does not take self or cls as an implicit first argument. It's essentially a regular function namespaced within the class. It cannot access or modify class or instance state.#65. What is
super()?A:
super() is a built-in function that returns a proxy object that allows you to refer to the parent class. It's commonly used in __init__ methods of child classes to call the parent class's __init__ method, ensuring that parent initializations are not missed.class Parent:
def __init__(self):
print("Parent init")
class Child(Parent):
def __init__(self):
super().__init__() # Call the Parent's init method
print("Child init")
c = Child()
Parent init
Child init
---
#66. What are public, protected, and private members?
A: These are conventions for encapsulation.
• Public: Accessible from anywhere. (e.g.,
member)• Protected: Conventionally treated as non-public; accessible within the class and its subclasses. Denoted by a single underscore prefix. (e.g.,
_member)• Private: Accessible only from within the class. Python enforces this through name mangling. Denoted by a double underscore prefix. (e.g.,
__member)#67. What is name mangling?
A: When an identifier starts with two underscores (like
__spam), it is textually replaced with _classname__spam. This is done to avoid naming conflicts with subclasses.#68. What are magic methods (or dunder methods)?
A: Magic methods are special methods with double underscores at the beginning and end of their names (e.g.,
__init__, __len__, __str__). They are not meant to be called directly but are invoked internally by Python in response to certain operations. For example, len(my_object) calls my_object.__len__().#69. Explain the difference between
__str__ and __repr__.A:
•
__str__(): Called by str(object) and print(object). It should return a user-friendly, readable string representation of the object.•
__repr__(): Called by repr(object). It should return an unambiguous, official string representation of the object, which can ideally be used to recreate the object (e.g., eval(repr(object)) == object). If __str__ is not defined, __repr__ is used as a fallback.#70. What is operator overloading?
A: Operator overloading allows you to redefine the behavior of built-in operators (like
---
Part 5: Advanced Concepts & Libraries (Q71-85)
#71. Explain exception handling in Python.
A: Exception handling is a mechanism for responding to runtime errors.
•
•
•
•
#72. How do you raise a custom exception?
A: You can define a custom exception by creating a new class that inherits from the built-in
#73. What is the purpose of the
A: The
#74. What is the difference between multithreading and multiprocessing?
A:
• Multithreading: Multiple threads run within the same process, sharing the same memory space. Due to the GIL, it's best for I/O-bound tasks (like network requests or file operations) where threads can wait without blocking the entire program.
• Multiprocessing: Multiple processes run, each with its own memory space and Python interpreter. This allows for true parallelism and is ideal for CPU-bound tasks (like heavy calculations) as it bypasses the GIL.
#75. What is the difference between a module and a package?
A:
• Module: A single Python file (
• Package: A way of organizing related modules into a directory hierarchy. A directory must contain a file named
---
#76. What are virtual environments? Why are they important?
A: A virtual environment is an isolated Python environment that allows you to manage dependencies for a specific project separately. They are important because they prevent package version conflicts between different projects on the same machine.
#77. What is
A:
A: Operator overloading allows you to redefine the behavior of built-in operators (like
+, -, *) for your custom classes. This is done by implementing the corresponding magic methods (e.g., __add__ for +, __mul__ for *).---
Part 5: Advanced Concepts & Libraries (Q71-85)
#71. Explain exception handling in Python.
A: Exception handling is a mechanism for responding to runtime errors.
•
try: The block of code to be attempted, which may cause an error.•
except: This block is executed if an error occurs in the try block. You can specify the type of exception to catch.•
else: This block is executed if no exceptions are raised in the try block.•
finally: This block is always executed, whether an exception occurred or not. It's often used for cleanup operations.try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Result is {result}")
finally:
print("Execution finished.")
Result is 5.0
Execution finished.
#72. How do you raise a custom exception?
A: You can define a custom exception by creating a new class that inherits from the built-in
Exception class. Then, use the raise keyword to throw it.class MyCustomError(Exception):
pass
raise MyCustomError("Something went wrong!")
#73. What is the purpose of the
with statement?A: The
with statement simplifies exception handling by encapsulating common try...finally cleanup patterns. It is used with objects that support the context management protocol (which have __enter__ and __exit__ methods). It's most commonly used for managing file streams, ensuring the file is closed automatically.# The file is automatically closed after this block
with open('file.txt', 'w') as f:
f.write('hello')
#74. What is the difference between multithreading and multiprocessing?
A:
• Multithreading: Multiple threads run within the same process, sharing the same memory space. Due to the GIL, it's best for I/O-bound tasks (like network requests or file operations) where threads can wait without blocking the entire program.
• Multiprocessing: Multiple processes run, each with its own memory space and Python interpreter. This allows for true parallelism and is ideal for CPU-bound tasks (like heavy calculations) as it bypasses the GIL.
#75. What is the difference between a module and a package?
A:
• Module: A single Python file (
.py) containing statements and definitions.• Package: A way of organizing related modules into a directory hierarchy. A directory must contain a file named
__init__.py (which can be empty) to be considered a package.---
#76. What are virtual environments? Why are they important?
A: A virtual environment is an isolated Python environment that allows you to manage dependencies for a specific project separately. They are important because they prevent package version conflicts between different projects on the same machine.
#77. What is
pip?A:
pip is the standard package manager for Python. It allows you to install and manage third-party libraries and packages from the Python Package Index (PyPI).#78. How does Python's
A: The
#79. What is the
A: The
#80. How do you work with JSON files in Python?
A: Use the built-in
•
•
---
#81. What is the
A: The
#82. What is monkey-patching?
A: Monkey-patching is a technique used to dynamically modify or extend code at runtime. For example, you can change the behavior of a function or a method in a third-party library without altering the original source code.
#83. What is a metaclass?
A: A metaclass is a "class of a class". It defines how a class behaves. A class is an instance of a metaclass. In Python,
#84. What is the difference between
A: This is a Python 2 question.
• In Python 2,
• In Python 3, the old
#85. What are some popular Python frameworks for web development?
A:
• Django: A high-level, "batteries-included" framework that encourages rapid development and clean, pragmatic design.
• Flask: A lightweight microframework that is simpler and more flexible, allowing developers to choose their own libraries and tools.
• FastAPI: A modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints.
---
Part 6: Coding Problems & Algorithms (Q86-100)
#86. Write a function to check if a string is a palindrome.
A: A palindrome reads the same forwards and backward. The easiest way is to compare the string with its reversed version.
#87. Write a Fibonacci sequence generator.
A: A generator is memory-efficient for this task.
for loop work internally?A: The
for loop in Python works with the iterator protocol. When you write for item in iterable:, Python first calls iter(iterable) to get an iterator object. Then, it repeatedly calls next() on this iterator object and assigns the result to item until a StopIteration exception is raised, which signals the end of the loop.#79. What is the
requests library used for?A: The
requests library is the de-facto standard for making HTTP requests in Python. It simplifies the process of interacting with web services and APIs.import requests
response = requests.get('https://api.github.com')
print(response.status_code)
200
#80. How do you work with JSON files in Python?
A: Use the built-in
json module.•
json.dump() / json.dumps(): To serialize a Python object into a JSON formatted stream or string.•
json.load() / json.loads(): To de-serialize a JSON formatted stream or string into a Python object.import json
data = {'name': 'John', 'age': 30}
json_string = json.dumps(data)
print(json_string)
{"name": "John", "age": 30}---
#81. What is the
os module used for?A: The
os module provides a way of using operating system-dependent functionality like reading or writing to the file system, interacting with environment variables, and managing directories.#82. What is monkey-patching?
A: Monkey-patching is a technique used to dynamically modify or extend code at runtime. For example, you can change the behavior of a function or a method in a third-party library without altering the original source code.
#83. What is a metaclass?
A: A metaclass is a "class of a class". It defines how a class behaves. A class is an instance of a metaclass. In Python,
type is the default metaclass. It's an advanced concept used for creating custom class behaviors.#84. What is the difference between
range() and xrange()?A: This is a Python 2 question.
• In Python 2,
range() created an actual list in memory, which was inefficient for very large ranges. xrange() created a generator-like object that yielded numbers on demand.• In Python 3, the old
range() was removed, and xrange() was renamed to range(). So, Python 3's range() behaves like Python 2's memory-efficient xrange().#85. What are some popular Python frameworks for web development?
A:
• Django: A high-level, "batteries-included" framework that encourages rapid development and clean, pragmatic design.
• Flask: A lightweight microframework that is simpler and more flexible, allowing developers to choose their own libraries and tools.
• FastAPI: A modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints.
---
Part 6: Coding Problems & Algorithms (Q86-100)
#86. Write a function to check if a string is a palindrome.
A: A palindrome reads the same forwards and backward. The easiest way is to compare the string with its reversed version.
def is_palindrome(s):
# Clean the string (optional, depends on requirements)
s = ''.join(filter(str.isalnum, s)).lower()
return s == s[::-1]
print(is_palindrome("A man, a plan, a canal: Panama"))
print(is_palindrome("racecar"))
print(is_palindrome("hello"))
True
True
False
#87. Write a Fibonacci sequence generator.
A: A generator is memory-efficient for this task.
❤1
def fibonacci_generator(n):
a, b = 0, 1
count = 0
while count < n:
yield a
a, b = b, a + b
count += 1
for num in fibonacci_generator(10):
print(num, end=' ')
0 1 1 2 3 5 8 13 21 34
#88. Solve the FizzBuzz problem.
A: Print numbers from 1 to n. But for multiples of three, print "Fizz" instead of the number, and for the multiples of five, print "Buzz". For numbers which are multiples of both three and five, print "FizzBuzz".
def fizzbuzz(n):
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
fizzbuzz(15)
#89. Find the factorial of a number using recursion.
A: The factorial of n is the product of all positive integers up to n.
def factorial(n):
if n < 0:
return "Factorial does not exist for negative numbers"
elif n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
120
#90. Reverse a string in Python.
A: The simplest and most Pythonic way is to use slicing.
my_string = "hello"
reversed_string = my_string[::-1]
print(reversed_string)
olleh
---
#91. Find the most frequent element in a list.
A: The
collections.Counter class is perfect for this.from collections import Counter
my_list = [1, 2, 3, 2, 4, 2, 5, 2]
count = Counter(my_list)
most_common_element = count.most_common(1)[0][0]
print(most_common_element)
2
#92. Check if two strings are anagrams.
A: Anagrams are words formed by rearranging the letters of another. If the sorted versions of the two strings are equal, they are anagrams.
def are_anagrams(s1, s2):
return sorted(s1) == sorted(s2)
print(are_anagrams("listen", "silent"))
print(are_anagrams("hello", "world"))
True
False
#93. Flatten a nested list.
A: This can be solved with recursion.
def flatten(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten(item))
else:
flat_list.append(item)
return flat_list
nested = [1, [2, 3], 4, [5, [6, 7]]]
print(flatten(nested))
[1, 2, 3, 4, 5, 6, 7]
#94. Find all pairs of an integer array whose sum is equal to a given number.
A: A hash set (or a dictionary) can be used to solve this in O(n) time.
def find_sum_pairs(arr, target_sum):
seen = set()
pairs = []
for num in arr:
complement = target_sum - num
if complement in seen:
pairs.append((complement, num))
seen.add(num)
return pairs
my_array = [2, 7, 4, 1, 5, 6]
print(find_sum_pairs(my_array, 8))
[(1, 7), (2, 6)]
#95. Write a simple decorator that logs the execution time of a function.
A: Use the
time module and wrap the function call.import time
def timer_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function {func.__name__} took {end_time - start_time:.4f} seconds to run.")
return result
return wrapper
@timer_decorator
def long_running_function():
time.sleep(1)
long_running_function()
Function long_running_function took 1.0010 seconds to run.
---
#96. Write a function that takes a list of numbers and returns a new list containing only the even numbers.
A: List comprehension is a great way to do this.
def filter_even_numbers(numbers):
return [num for num in numbers if num % 2 == 0]
my_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(filter_even_numbers(my_numbers))
[2, 4, 6, 8, 10]
#97. Explain what
* does when unpacking a list or tuple.A: The
* operator can be used to unpack an iterable into individual elements. It's often used for function arguments or in assignments.numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
print(f"First: {first}")
print(f"Middle: {middle}")
print(f"Last: {last}")
First: 1
Middle: [2, 3, 4]
Last: 5
#98. Write a function to merge two sorted lists into a single sorted list.
A: You can simply concatenate them and sort, but a more efficient approach (O(n+m)) is to iterate through both lists simultaneously.
def merge_sorted_lists(list1, list2):
# The simple, Pythonic way
return sorted(list1 + list2)
l1 = [1, 3, 5]
l2 = [2, 4, 6]
print(merge_sorted_lists(l1, l2))
[1, 2, 3, 4, 5, 6]
#99. What will be the output of the following code?
A: This question tests understanding of mutable default arguments.
def my_func(item, my_list=[]):
my_list.append(item)
return my_list
print(my_func(1))
print(my_func(2))
print(my_func(3))
[1]
[1, 2]
[1, 2, 3]
The default list is created only once when the function is defined. It is then shared across all subsequent calls, leading to this surprising behavior. The correct way is to use
my_list=None as the default.#100. How would you count the occurrences of each word in a given text sentence?
A: The
collections.Counter is the ideal tool for this task.from collections import Counter
import re
sentence = "The quick brown fox jumps over the lazy dog dog"
# Pre-process: lowercase and split into words
words = re.findall(r'\w+', sentence.lower())
word_counts = Counter(words)
print(word_counts)
Counter({'the': 2, 'dog': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1})━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❤3
💡 Top 50 Operations for Text Processing in Python
I. Case & Whitespace Manipulation
• Convert to lowercase.
• Convert to uppercase.
• Capitalize the first letter of the string.
• Convert to title case (each word starts with a capital).
• Swap character case.
• Remove leading and trailing whitespace.
• Remove leading whitespace.
• Remove trailing whitespace.
II. Searching, Replacing & Counting
• Find the first index of a substring.
• Check if a string starts with a substring.
• Check if a string ends with a substring.
• Replace a substring with another.
• Count occurrences of a substring.
III. Splitting & Joining
• Split a string into a list of words.
• Join a list of strings into a single string.
• Split a string into lines.
• Partition a string at the first occurrence of a separator.
IV. Character & String Checks
• Check if all characters are alphabetic.
• Check if all characters are digits.
• Check if all characters are alphanumeric.
• Check if all characters are whitespace.
V. Regular Expressions (
• Find the first match of a pattern.
• Find all matches of a pattern.
• Substitute a pattern with a replacement string.
• Split a string by a regex pattern.
VI. Basic NLP - Tokenization & Cleaning
(Requires
• Sentence Tokenization.
• Word Tokenization.
• Remove punctuation.
• Remove stop words.
I. Case & Whitespace Manipulation
• Convert to lowercase.
text = "Hello World"
lower_text = text.lower()
• Convert to uppercase.
upper_text = text.upper()
• Capitalize the first letter of the string.
capitalized = "hello world".capitalize()
• Convert to title case (each word starts with a capital).
title_text = "hello world".title()
• Swap character case.
swapped = "Hello World".swapcase()
• Remove leading and trailing whitespace.
padded_text = " hello "
stripped_text = padded_text.strip()
• Remove leading whitespace.
left_stripped = padded_text.lstrip()
• Remove trailing whitespace.
right_stripped = padded_text.rstrip()
II. Searching, Replacing & Counting
• Find the first index of a substring.
index = "hello world".find("world") # Returns 6• Check if a string starts with a substring.
starts_with_hello = text.startswith("Hello") # True• Check if a string ends with a substring.
ends_with_world = text.endswith("World") # True• Replace a substring with another.
new_text = text.replace("World", "Python")• Count occurrences of a substring.
count = "hello hello".count("hello") # Returns 2III. Splitting & Joining
• Split a string into a list of words.
words = text.split(' ') # ['Hello', 'World']• Join a list of strings into a single string.
word_list = ["Hello", "Python"]
joined_text = " ".join(word_list)
• Split a string into lines.
multiline = "line one\nline two"
lines = multiline.splitlines()
• Partition a string at the first occurrence of a separator.
parts = "user@domain.com".partition('@') # ('user', '@', 'domain.com')IV. Character & String Checks
• Check if all characters are alphabetic.
"HelloWorld".isalpha() # True
• Check if all characters are digits.
"12345".isdigit() # True
• Check if all characters are alphanumeric.
"Python3".isalnum() # True
• Check if all characters are whitespace.
" \t\n".isspace() # True
V. Regular Expressions (
re module)• Find the first match of a pattern.
import re
match = re.search(r'\d+', 'There are 10 apples.')
• Find all matches of a pattern.
numbers = re.findall(r'\d+', '10 apples and 20 oranges')
• Substitute a pattern with a replacement string.
no_digits = re.sub(r'\d', '#', 'My pin is 1234')
• Split a string by a regex pattern.
items = re.split(r'[,;]', 'apple,banana;cherry')
VI. Basic NLP - Tokenization & Cleaning
(Requires
pip install nltk)• Sentence Tokenization.
from nltk.tokenize import sent_tokenize
# nltk.download('punkt') # Run once
text = "Hello Mr. Smith. How are you?"
sentences = sent_tokenize(text)
• Word Tokenization.
from nltk.tokenize import word_tokenize
words = word_tokenize("Hello, how are you?")
• Remove punctuation.
import string
text = "A string with... punctuation!"
clean = text.translate(str.maketrans('', '', string.punctuation))
• Remove stop words.
from nltk.corpus import stopwords
# nltk.download('stopwords') # Run once
stop_words = set(stopwords.words('english'))
filtered = [w for w in words if not w.lower() in stop_words]
VII. Word Normalization (Stemming & Lemmatization)
• Stemming (reduce words to their root form).
from nltk.stem import PorterStemmer
ps = PorterStemmer()
stemmed = ps.stem("running") # 'run'
• Lemmatization (reduce words to their dictionary form).
from nltk.stem import WordNetLemmatizer
# nltk.download('wordnet') # Run once
lemmatizer = WordNetLemmatizer()
lemma = lemmatizer.lemmatize("better", pos="a") # 'good'
VIII. Advanced NLP Analysis
(Requires
pip install spacy and python -m spacy download en_core_web_sm)• Part-of-Speech (POS) Tagging.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Apple is looking at buying a U.K. startup.")
for token in doc: print(token.text, token.pos_)
• Named Entity Recognition (NER).
for ent in doc.ents:
print(ent.text, ent.label_) # Apple ORG, U.K. GPE
• Get word frequency distribution.
from nltk.probability import FreqDist
fdist = FreqDist(word_tokenize("this is a test this is only a test"))
IX. Text Formatting & Encoding
• Format strings with f-strings.
name = "Alice"
age = 30
message = f"Name: {name}, Age: {age}"
• Pad a string with leading zeros.
number = "42".zfill(5) # '00042'
• Encode a string to bytes.
byte_string = "hello".encode('utf-8')• Decode bytes to a string.
original_string = byte_string.decode('utf-8')X. Text Vectorization
(Requires
pip install scikit-learn)• Create a Bag-of-Words (BoW) model.
from sklearn.feature_extraction.text import CountVectorizer
corpus = ["This is the first document.", "This is the second document."]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(corpus)
• Get feature names (the vocabulary).
print(vectorizer.get_feature_names_out())
• Create a TF-IDF model.
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(corpus)
XI. More String Utilities
• Center a string within a width.
centered = "Hello".center(20, '-') # '-------Hello--------'
• Check if a string is in title case.
"This Is A Title".istitle() # True
• Find the highest index of a substring.
"test test".rfind("test") # Returns 5• Split from the right.
"path/to/file.txt".rsplit('/', 1) # ['path/to', 'file.txt']• Create a character translation table.
table = str.maketrans('aeiou', '12345')
vowels_to_num = "hello".translate(table) # 'h2ll4'• Remove a specific prefix.
"TestCase".removeprefix("Test") # 'Case'• Remove a specific suffix.
"filename.txt".removesuffix(".txt") # 'filename'• Check for unicode decimal characters.
"½".isdecimal() # False
"123".isdecimal() # True
• Check for unicode numeric characters.
"½".isnumeric() # True
"²".isnumeric() # True
#Python #TextProcessing #NLP #RegEx #NLTK
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
✨ LlamaIndex | AI Coding Tools ✨
📖 A high-level framework for building RAG and agentic applications.
🏷️ #Python
📖 A high-level framework for building RAG and agentic applications.
🏷️ #Python