Interview Prep

MNC Edition: Google, Amazon, TCS

Variables What is a variable in Python and how is it created?
πŸ“Œ Explanation
A variable is a name that stores a value in memory. Python automatically creates the variable when a value is assigned.
βœ” Python is dynamically typed βœ” No need to declare variable types
Example

x = 10
name = "Hari"
pi = 3.14

print(x, name, pi)
Variables What is dynamic typing in Python?
πŸ“Œ Explanation
Python allows variables to change their type during execution. This is called dynamic typing.
⚠️ Dynamic typing makes Python flexible but can cause unexpected bugs.
Practice

x = 10       # int
x = "Python" # now string

print(type(x))
Variables How are variables stored in memory? Explain with example.
πŸ“Œ Explanation
Variables store references to memory locations, not actual values. Python internally uses a system of memory blocks where values live, and variables simply point to them.
βœ” Multiple variables can point to the same memory value βœ” Memory is freed when reference count becomes 0
Practice

a = 10
b = a  # both refer to the same memory address

print(id(a), id(b))
Variables What are variable naming rules in Python?
πŸ“Œ Rules
βœ” Must start with a letter or underscore (_)
βœ” Cannot start with a number
βœ” Only letters, numbers, and underscores allowed
βœ” Case-sensitive (age β‰  Age)
βœ” Cannot use reserved keywords
❌ Invalid names: 2name, first-name, class
Practice

_name = "valid"
age2 = 20
PersonName = "Hari"

print(_name, age2, PersonName)
Variables How do you modify a global variable inside a function?
πŸ“Œ Explanation
To modify a global variable inside a function, you must use the global keyword. Otherwise, Python treats it as a local variable.
⚠️ Overusing global is not good practice; use return values instead.

counter = 0

def increase():
    global counter
    counter += 1

increase()
print(counter)
Variables What are constants in Python? How do you define one?
πŸ“Œ Explanation
Python does not have true constants, but developers use UPPERCASE names to represent values that should not change.
βœ” Constants are only conventions βœ” Python will still allow modification

PI = 3.14159
APP_NAME = "DSPython"
MAX_USERS = 100

print(PI, APP_NAME, MAX_USERS)
Variables What is multiple assignment in Python?
πŸ“Œ Explanation
Python allows assigning multiple values to multiple variables in one line.
βœ” Helps write cleaner and shorter code βœ” Widely used in swapping variables

a, b, c = 10, 20, 30
print(a, b, c)

# swapping
x, y = 5, 9
x, y = y, x
print(x, y)
Variables What is variable unpacking in Python?
πŸ“Œ Explanation
Variable unpacking means assigning values from a list/tuple directly into variables.
βœ” Useful when working with sequences βœ” Helps keep code clean & readable

numbers = [10, 20, 30]
a, b, c = numbers

print(a, b, c)
Variables What are temporary variables? How can you avoid using them?
Temporary variables are variables used only to hold intermediate values. Python allows avoiding them using tuple unpacking.

x, y = 10, 20

# Normal swap using temp variable
temp = x
x = y
y = temp

# Pythonic swap without temp
x, y = y, x
Variables What is shadowing of variables? Give an example.
Variable shadowing happens when a local variable has the same name as a global variable, hiding the global one inside that scope.

value = 100  
def show():
    value = 50  # shadows global variable
    print(value)

show()
print(value)
Variables Why does Python allow reassigning variables to different types?
Python uses dynamic typing, meaning the variable name only references an object. The object determines the type, not the variable.

x = 10
print(x, type(x))

x = "Python"
print(x, type(x))
Variables What is the difference between assignment = and comparison ==?
= assigns a value to a variable. == checks whether two values are equal.

x = 10        # assignment
y = 10

print(x == y)  # True β€” comparison
Data Types What are the main built-in data types in Python?
Python supports several built-in data types such as:
Numeric (int, float, complex), Sequence (list, tuple, range, string), Set (set, frozenset), Mapping (dict), Boolean, None.

x = 10               # int
y = 3.14             # float
name = "Hari"        # str
nums = [1, 2, 3]     # list
data = {"age": 22}  # dict
Data Types How do you check the type of a variable in Python?
Python provides the built-in type() function to check the type of a variable.

x = "Python"
print( type(x) )
Data Types What is the difference between mutable and immutable data types?
Mutable: Can be changed β†’ list, dict, set Immutable: Cannot be changed β†’ int, float, str, tuple

nums = [1, 2]
nums.append(3)     # mutable

name = "Hari"
print(name.upper())   # creates new string (immutable)
Data Types How does Python store large integers internally?
Python integers have **unlimited precision**. Internally, Python converts large integers into a variable-length array of digits (base-230 blocks).

big = 9999999999999999999999999
print(big.bit_length())   # internal bit size
Data Types What is the difference between list and tuple in Python?
List β†’ Mutable, slower, takes more memory, best for dynamic collections.
Tuple β†’ Immutable, faster, hashable, can be used as dictionary keys.

my_list = [1, 2, 3]
my_tuple = (1, 2, 3)

my_list.append(4)        # OK
# my_tuple.append(4) β†’ Error (immutable)
Data Types What is the difference between set and frozenset?
set β†’ Mutable, cannot be used as dictionary keys. frozenset β†’ Immutable, hashable, can be used as dictionary keys.

s = {1, 2}
fs = frozenset({1, 2})

s.add(3)         # allowed
# fs.add(3) β†’ Error (immutable)
Data Types How do dictionaries handle collisions internally?
Python dictionaries use **open addressing with probing**. When a hash collision occurs, Python searches the next free slot in the table.

d = { }
d["a"] = 1
d["b"] = 2

print(d)
Data Types What is type casting? Explain with an example.
Type casting means converting one data type to another explicitly using functions like:
int(), float(), str(), list(), tuple().

x = "10"
y = int(x)        # "10" β†’ 10

z = float("3.5")  # "3.5" β†’ 3.5

nums = list((1, 2, 3))   # tuple β†’ list
Data Types What is the difference between int, float, and complex numbers?
int β†’ whole numbers float β†’ decimal values complex β†’ numbers with real + imaginary part (x + yj)

a = 10                     # int
b = 3.14                   # float
c = 2 + 5j                 # complex

print(type(c))     # <class 'complex'>
Data Types What is type inference in Python? How does Python decide the type?
Python is **dynamically typed**. It decides the variable type **at runtime** based on the assigned value.

x = 10                 # int
x = "Hari"           # now str

print(type(x))
Data Types How does Python store large integers internally?
Python automatically allocates more memory for very large integers. It does NOT overflow like C/C++ β€” integers grow dynamically.

big = 9999999999999999999999999999
print(big ** 2)      # Python handles huge values
Data Types What is the difference between bytes and bytearray?
bytes β†’ immutable bytearray β†’ mutable version of bytes Both store raw binary data (0–255).

b  = bytes([65, 66, 67])
ba = bytearray([65, 66, 67])

# ba[0] = 90   # allowed (mutable)
# b[0] = 90    # error (immutable)

print(b, ba)
Data Types How does Python internally represent Boolean values?
Python stores True as integer 1 and False as integer 0. Boolean is actually a subclass of int.

print(True + 5)     # 6
print(False + 5)    # 5
print(isinstance(True, int)) 
Data Types What is the difference between None and 0 and False?
None β†’ absence of value 0 β†’ integer False β†’ boolean All three behave differently but evaluate to False in conditions.

x = None
y = 0
z = False

print(bool(x), bool(y), bool(z))  # False False False
Data Types What is the role of type() and isinstance()?
type(obj) β†’ returns exact class of object isinstance(obj, Class) β†’ returns True even for subclass objects (Recommended for OOP-based checks.)

class A: pass
class B(A): pass

obj = B()

print(type(obj) == A)          # False
print(isinstance(obj, A))      # True
Data Types How do you convert between different numeric types (int, float, complex)?
Python supports explicit numeric conversions using int(), float(), complex().

x = 10
y = float(x)          # 10.0
z = complex(y)        # (10+0j)

print(x, y, z)
Operators What are arithmetic operators? Explain with examples.
Arithmetic operators perform basic mathematical operations.

a = 10
b = 3

print(a + b)   # addition
print(a - b)   # subtraction
print(a * b)   # multiplication
print(a / b)   # division
print(a % b)   # modulus

                
Operators What are comparison operators? Give examples.
Comparison operators compare values and return True/False.

print(5 > 3)    # True
print(5 < 3)    # False
print(5 == 5)   # True
print(5 != 2)   # True
print(5 >= 5)   # True

                
Operators Explain logical operators with a real example.
Logical operators combine conditions: and, or, not.

age = 20
is_student = True

print(age >= 18 and is_student)   # True
print(age < 18 or is_student)     # True
print(not is_student)             # False

                
Operators What are assignment operators? Explain +=, -=, *=.
Assignment operators modify variables in-place.

x = 10
x += 5    # x = x + 5
x -= 3    # x = x - 3
x *= 2    # x = x * 2

print(x)

                
Operators Explain identity operators is and is not.
Identity operators compare memory locations.

a = [1,2]
b = [1,2]
c = a

print(a is b)      # False (different objects)
print(a is c)      # True (same object)
print(a is not b)  # True

                
Operators Explain membership operators in and not in.
Membership operators check if a value exists inside a sequence.

fruits = ["apple", "banana"]

print("apple" in fruits)       # True
print("mango" not in fruits)   # True

                
Operators Explain bitwise operators (&, |, ^, ~, <<, >>).

a = 10   # 1010
b = 4    # 0100

print(a & b)   # AND
print(a | b)   # OR
print(a ^ b)   # XOR
print(~a)      # NOT
print(a << 1)  # Left shift
print(a >> 1)  # Right shift

                
Operators What is operator precedence? Give an example.

result = 10 + 5 * 2   
# multiplication runs first β†’ 10 + 10 = 20

print(result)

                
Operators Difference between == and is (operator perspective).
== compares values, is compares memory location.

x = [1,2]
y = [1,2]

print(x == y)   # True
print(x is y)   # False

                
Operators Write a program using ternary operator.

age = 17
status = "Adult" if age >= 18 else "Minor"

print(status)

                
Operators Show an example where logical operators avoid errors (short-circuit).

x = None

if x and x > 5:
    print("Greater")
# No error because second condition is skipped

                
Operators Create a small calculator using operators.

a = 12
b = 4

print(a + b)
print(a - b)
print(a * b)
print(a / b)

                
Strings Q1. What is a string in Python and how do you create one?

A string is an ordered sequence of characters enclosed in quotes. In Python you can use single (') or double (") quotes.

Interview Tip: Strings are immutable – you cannot change them in-place.

name = "Hari"
greet = 'Hello'

# concatenation
message = greet + " " + name
print(message)   # Hello Hari
Strings Q2. How does string indexing and slicing work in Python?

Strings support zero-based indexing (first char at index 0) and slicing with the syntax s[start:stop:step]. Negative indices count from the end.

s = "Python"

print(s[0])      # P
print(s[-1])     # n
print(s[1:4])    # yth
print(s[::2])    # Pto (step 2)

Practice: Try to slice "DataScience" to get "Data", "Science", and "Sci".

Strings Q3. What does it mean that strings are immutable? Show with an example.

Immutable means you cannot change a string's characters by index. Any β€œmodification” creates a new string object.

s = "hello"

# ❌ This raises TypeError
# s[0] = "H"

# βœ… Correct way: create a new string
s2 = "H" + s[1:]
print(s2)   # Hello

Interview Tip: Immutability makes strings hashable, so they can be safely used as dictionary keys and set elements.

Strings Q4. What are some common string methods used in interviews?

Common methods: lower(), upper(), strip(), split(), join(), replace().

s = "  Hello, Python  "

print(s.strip())                 # remove spaces both sides
print(s.lower())                 # to lowercase

parts = s.strip().split(",")
print(parts)                      # ['Hello', ' Python']

words = ["Data", "Science"]
print(" ".join(words))      # Data Science

Practice: Use these methods to clean a comma-separated string of emails.

Strings Q5. How do you check if a string is a palindrome (ignoring case and spaces)?

Palindrome means the string reads the same forwards and backwards. Use normalization (lowercase + remove spaces) and compare with its reverse.

def is_palindrome(s):
    clean = s.replace(" ", "").lower()
    rev = clean[::-1]
    return clean == rev

print(is_palindrome("Madam"))          # True
print(is_palindrome("nurses run"))    # True
Strings Q6. How do you count the frequency of each character in a string?

Use a dictionary (or collections.Counter) to store character counts.

s = "banana"
freq = {}

for ch in s:
    freq[ch] = freq.get(ch, 0) + 1

print(freq)   # {'b':1, 'a':3, 'n':2}

Follow-up: Modify this to count words instead of characters.

STRINGS Q7. How do you reverse the words in a sentence but keep characters in each word same?

To reverse only the order of words while keeping characters inside each word untouched, split the string by spaces, reverse the list, and join it back.


sentence = "Python is super easy"

words = sentence.split()
reversed_words = words[::-1]
result = " ".join(reversed_words)

print(result) 
# Output: easy super is Python
                

Concept: βœ” Split β†’ βœ” Reverse list β†’ βœ” Join β†’ Characters inside each word stay unchanged.

Strings Q8. Write a program to count vowels and consonants in a string.

Normalize to lowercase, then check each character against a vowel set.

def count_vowels_consonants(s):
    vowels = "aeiou"
    v = c = 0
    for ch in s.lower():
        if ch.isalpha():
            if ch in vowels:
                v += 1
            else:
                c += 1
    return v, c

print(count_vowels_consonants("Interview"))
Strings Q9. Explain isalpha(), isdigit(), and isalnum() with a validation example.

These methods help in input validation: isalpha() β†’ only letters, isdigit() β†’ only digits, isalnum() β†’ letters or digits.

username = "hari123"
age = "22"

if username.isalnum() and age.isdigit():
    print("Valid input")
else:
    print("Invalid")
Strings Q10. How do you format strings using f-strings and format()?

f-strings are the modern, readable way introduced in Python 3.6. format() is older but still common in interviews.

name = "Hari"
score = 95.4567

# f-string
print(f"{name} scored {score:.2f}")

# format()
print("{0} scored {1:.2f}".format(name, score))
Strings Q11. Remove duplicate characters from a string but keep the original order.

Use a set to track seen characters and build a new string. This is a common coding task to test your understanding of strings + sets.

s = "programming"
seen = set()
result = []

for ch in s:
    if ch not in seen:
        seen.add(ch)
        result.append(ch)

print("".join(result))   # progamin
Strings Q12. Find the longest word in a given sentence.

Split the sentence into words and use max() with key=len. This is a very common string + built-in functions question.

s = "Python interview preparation guide"

words = s.split()
longest = max(words, key=len)

print(longest)   # preparation
LISTS Q1. What is a list in Python? Why is it considered mutable?

A list is an ordered, mutable collection used to store multiple items. Mutable means you can add, remove, or update values after creation.


nums = [10, 20, 30]
nums[1] = 25      # list is mutable
print(nums)

LISTS Q2. How do you access, update, and delete list items in Python?

nums = [10, 20, 30, 40]

print(nums[2])   # access
nums[1] = 50     # update
del nums[3]      # delete

print(nums)

LISTS Q3. What are list slicing operations? Give examples.

nums = [10, 20, 30, 40, 50]

print(nums[1:4])   # middle slice
print(nums[:3])    # start slice
print(nums[2:])    # end slice
print(nums[::-1])  # reverse list

LISTS Q4. What is list comprehension? Rewrite a loop using comprehension.

# normal loop
squares = []
for x in range(5):
    squares.append(x*x)

# list comprehension
squares2 = [x*x for x in range(5)]

print(squares2)

LISTS Q5. Explain append(), insert(), extend() with examples.

nums = [1, 2]

nums.append(3)        # add at end
nums.insert(1, 10)    # insert at index
nums.extend([20, 30]) # add multiple

print(nums)

LISTS Q6. Compare remove(), pop(), and clear() with examples.

nums = [10, 20, 30, 40]

nums.remove(20)   # remove by value
nums.pop(1)       # remove by index
nums.clear()      # delete all items

print(nums)

LISTS Q7. How do you sort a list in ascending and descending order?

nums = [5, 2, 9, 1]

print(sorted(nums))           # ascending
print(sorted(nums, reverse=True))  # descending

nums.sort()                   # in-place
nums.sort(reverse=True)

LISTS Q8. What is shallow copy vs deep copy in lists?

import copy

a = [[1,2], [3,4]]
b = a.copy()            # shallow copy
c = copy.deepcopy(a)    # deep copy

a[0][0] = 99

print(b)  # changed (shares nested lists)
print(c)  # unchanged (full clone)

LISTS Q9. Write a program to remove duplicates from a list while keeping order.

nums = [10, 20, 10, 30, 20]
unique = []

for n in nums:
    if n not in unique:
        unique.append(n)

print(unique)

LISTS Q10. Write Python code to flatten a nested list.

nested = [[1,2], [3,4], [5,6]]
flat = [x for group in nested for x in group]

print(flat)

LISTS Q11. Write a program to find the second largest element in a list.

nums = [10, 50, 30, 40, 50]

unique = list(set(nums))
unique.sort()

print(unique[-2])

LISTS Q12. How do you zip two lists together? Give an example.

names = ["A", "B", "C"]
scores = [90, 85, 88]

pairs = list(zip(names, scores))
print(pairs)

TUPLES Q1. What is a tuple in Python? How is it different from a list?

A tuple is an immutable ordered collection. Lists are mutable; tuples are not.

# List vs Tuple
my_list = [1, 2, 3]      # mutable
my_tuple = (1, 2, 3)     # immutable
                
TUPLES Q2. How do you create a tuple? Show all possible ways.
# Normal tuple
t1 = (1, 2, 3)

# Without parentheses
t2 = 1, 2, 3

# Single element tuple
t3 = (5,)       # comma required

# Using tuple()
t4 = tuple([1, 2, 3])
            
TUPLES Q3. Why are tuples faster than lists? When should you use tuples?

Tuples use less memory and are stored in compact structures. Python optimizes them internally.

# Faster iteration
my_tuple = (1, 2, 3)
for x in my_tuple:
    print(x)
            
TUPLES Q4. Can you modify a tuple? How do you β€œupdate” a tuple if needed?

Tuples cannot be modified. But you can create a new tuple from the old one.

t = (1, 2, 3)
t_new = t + (4, 5)     # creates a new tuple
print(t_new)
            
TUPLES Q5. How do indexing and slicing work on tuples?
t = (10, 20, 30, 40)

print(t[0])     # 10
print(t[-1])    # 40
print(t[1:3])   # (20, 30)
            
TUPLES Q6. How do you unpack tuple values?
a, b, c = (1, 2, 3)
print(a, b, c)

# Extended unpacking
x, *y = (5, 6, 7, 8)
print(x)   # 5
print(y)   # [6, 7, 8]
            
TUPLES Q7. How do you check membership in a tuple?
t = (1, 2, 3, 4)
print(3 in t)       # True
print(10 in t)      # False
            
TUPLES Q8. How do you convert a list to a tuple and a tuple to a list?
lst = [1, 2, 3]
t = tuple(lst)

t2 = (4, 5, 6)
lst2 = list(t2)
            
TUPLES Q9. Can tuples hold mutable objects? What happens if you modify them?
t = (1, [2, 3], 4)

t[1].append(99)   # allowed (list is mutable)
print(t)          # (1, [2, 3, 99], 4)
            
TUPLES Q10. When are tuples hashable? Why is this important?

A tuple is hashable only if all its elements are immutable.

# Valid key
d = {(1, 2, 3): "OK"}

# Invalid (list is mutable)
# d = {([1,2], 3): "error"}
            
TUPLES Q11. How do you count occurrences and find index inside a tuple?
t = (1, 2, 2, 3, 3, 3)

print(t.count(3))     # 3
print(t.index(2))     # first occurrence
            
TUPLES Q12. Give a real-time use case of tuples in Python. Why choose a tuple instead of a list?

Example: Returning multiple values from a function (safe, immutable).

def get_user():
    return ("Hari", 22, "Hyderabad")   # tuple result

name, age, city = get_user()
            
Sets Q1. What is a Set in Python?
Definition: A set is an unordered collection of unique elements.
Example: {1, 2, 3} β†’ duplicates are automatically removed.

my_set = {1, 2, 2, 3}
print(my_set)  
# Output: {1, 2, 3}

                
Sets Q2. How do you create a set in Python?
Definition: Sets can be created using { } or set().
Example: set([1, 2, 3]) creates a set from a list.

s1 = {1, 2, 3}
s2 = set([4, 5, 6])

print(s1, s2)

                
Sets Q3. How do you add or update elements in a set?
Definition: Use add() for single element and update() for multiple elements.
Example: s.add(10) β†’ adds 10 to set.

s = {1, 2, 3}
s.add(4)
s.update([5, 6])

print(s)

                
Sets Q4. How do you remove elements from a set?
Definition: Use remove(), discard(), or pop().
Example: discard() does not throw error if element doesn't exist.

s = {1, 2, 3}

s.remove(2)   # errors if missing
s.discard(5)  # safe
val = s.pop() # removes random element

print(s)

                
Sets Q5. What is set union in Python?
Definition: Union combines elements of two sets, removing duplicates.
Example: {1,2} βˆͺ {2,3} β†’ {1,2,3}

a = {1, 2}
b = {2, 3}

print(a.union(b)) 
print(a | b)

Sets Q6. What is intersection of sets?
Definition: Intersection returns only the elements present in both sets.
Example: {1,2} ∩ {2,3} β†’ {2}

a = {1, 2}
b = {2, 3}

print(a.intersection(b))
print(a & b)

Sets Q7. What is the difference between difference() and symmetric_difference()?
Definition: difference() β†’ elements present in A but not in B. symmetric_difference() β†’ elements present in either set but not both.
Example: {1,2,3} - {2} β†’ {1,3} {1,2,3} Ξ” {2,4} β†’ {1,3,4}

a = {1, 2, 3}
b = {2, 4}

print(a.difference(b))            # {1, 3}
print(a.symmetric_difference(b))  # {1, 3, 4}

Sets Q8. How do you check if one set is a subset or superset of another?
Definition: subset: every element of A exists in B superset: A contains all elements of B Example: {1,2} βŠ† {1,2,3}

a = {1, 2}
b = {1, 2, 3}

print(a.issubset(b))   # True
print(b.issuperset(a)) # True

Sets Q9. How do you convert a list into a set and remove duplicates?
Definition: Use set(list) to remove duplicates.
Example: set([1,1,2,3]) β†’ {1,2,3}

nums = [1, 1, 2, 3, 3]
unique = set(nums)
print(unique)

Sets Q10. Why are sets faster for membership testing?
Definition: Sets use hash tables, giving O(1) average lookup time.
Example: Checking if x in set is faster than in list.

s = {1, 2, 3}
print(3 in s)  # True, fast O(1)

Sets Q11. Can sets store mutable objects?
Definition: Sets can store only hashable (immutable) items.
Example: Lists cannot be added, but tuples can.

s = set()
s.add((1, 2))  # valid
# s.add([1, 2]) β†’ error (list is mutable)

Sets Q12. Explain frozen sets and where they are useful.
Definition: A frozen set is an immutable set that cannot be modified.
Example: Useful as dictionary keys or elements of other sets.

fs = frozenset([1, 2, 3])
print(fs)

# fs.add(4) β†’ error (immutable)

Dict Q1. What is a dictionary in Python?
Definition: A dictionary stores data in key–value pairs.
Example: {"name": "Hari", "age": 22}

student = {"name": "Hari", "age": 22}
print(student["name"])

Dict Q2. How do you access values in a dictionary?
Definition: Values are accessed using keys inside brackets.
Example: person["age"]

person = {"name": "Ravi", "age": 30}
print(person["age"])
print(person.get("name"))

Dict Q3. How do you add or update items in a dictionary?
Definition: Assigning to a key adds or updates its value.
Example: d["city"] = "Hyderabad"

d = {"name": "Hari"}
d["age"] = 22
d["age"] = 23  # update

print(d)

Dict Q4. How do you remove items from a dictionary?
Definition: Use pop(), del, or popitem().
Example: del d["name"]

d = {"name": "Hari", "age": 22}

d.pop("age")
del d["name"]
print(d)

Dict Q5. How do you iterate through keys, values, and items?
Definition: Use keys(), values(), and items().
Example: Key-value looping with items().

d = {"a": 1, "b": 2}

for k in d.keys():
    print(k)

for v in d.values():
    print(v)

for k, v in d.items():
    print(k, v)

Dict Q6. What is the use of get() vs direct indexing?
Definition: get() avoids KeyError when key is absent.
Example: d.get("x", 0)

d = {"a": 10}

print(d.get("b"))      # None
print(d.get("b", 0))   # default value
# print(d["b"]) β†’ KeyError

Dict Q7. What is dictionary comprehension?
Definition: A shorthand way to create dictionaries in one line.
Example: {x: x*x for x in range(3)}

squares = {x: x*x for x in range(5)}
print(squares)

Dict Q8. How do you merge two dictionaries?
Definition: Use | operator or update().
Example: d3 = d1 | d2

d1 = {"a": 1}
d2 = {"b": 2}

print(d1 | d2)

Dict Q9. What are nested dictionaries?
Definition: A dictionary inside another dictionary.
Example: {"emp": {"name": "Sam"}}

company = {
    "emp1": {"name": "Hari", "age": 22},
    "emp2": {"name": "Ravi", "age": 30}
}

print(company["emp1"]["name"])

Dict Q10. Why are dictionary keys required to be immutable?
Definition: Immutable keys can be safely hashed and stored in hash tables.
Example: integers, strings, tuples are valid keys.

d = {}
d["name"] = "Hari"     # valid
# d[[1, 2]] = "x"      # error: unhashable type 'list'

Dict Q11. How do you sort a dictionary by keys or values?
Definition: Use sorted() with key parameter.
Example: sort by value β†’ key=lambda x: x[1]

d = {"b": 3, "a": 1, "c": 2}

print(sorted(d.items()))                      # by key
print(sorted(d.items(), key=lambda x: x[1]))  # by value

Dict Q12. What is defaultdict and how is it different from normal dict?
Definition: defaultdict creates missing keys automatically with a default value.
Example: defaultdict(int) β†’ default 0.

from collections import defaultdict

d = defaultdict(int)
d["a"] += 1
print(d)  # {'a': 1}

If Q1. What are conditional statements in Python?
Definition: Conditional statements allow Python to execute code only when a condition is True.
Example: if age >= 18:

age = 20
if age >= 18:
    print("Eligible to vote")

If Q2. What is the structure of an if–else statement?
Definition: The if–else block chooses between two actions based on a condition.
Example: if x % 2 == 0:

x = 7
if x % 2 == 0:
    print("Even")
else:
    print("Odd")

If Q3. What is elif and when do we use it?
Definition: elif allows checking multiple conditions in sequence.
Example: grading system.

marks = 82

if marks >= 90:
    print("A Grade")
elif marks >= 75:
    print("B Grade")
else:
    print("C Grade")

If Q4. Can if–elif–else have multiple elif blocks?
Definition: Yes, Python supports as many elif blocks as needed.
Example: Temperature classification.

temp = 32

if temp > 40:
    print("Hot")
elif temp > 30:
    print("Warm")
elif temp > 20:
    print("Cool")
else:
    print("Cold")

If Q5. What is a nested if statement?
Definition: When an if statement exists inside another if block.
Example: Checking age + ID card.

age = 19
has_id = True

if age >= 18:
    if has_id:
        print("Entry allowed")

If Q6. What is a ternary (inline) if expression?
Definition: A compact one-line if–else expression.
Example: x = "Even" if n % 2 == 0 else "Odd"

n = 4
result = "Even" if n % 2 == 0 else "Odd"
print(result)

If Q7. Can conditions use logical operators (and/or/not)?
Definition: Yes, conditions can combine multiple checks.
Example: age >= 18 and country == "IN"

age = 20
country = "IN"

if age >= 18 and country == "IN":
    print("Eligible")

If Q8. What is short-circuit evaluation in if statements?
Definition: Python stops evaluating further conditions if result is already known.
Example: False and heavy_function()

x = 0
if x != 0 and (10 / x) > 1:
    print("Won't run")

If Q9. How do comparisons chain in Python?
Definition: Python supports chained comparisons like math notation.
Example: 3 < x < 10

x = 5
if 3 < x < 10:
    print("In range")

If Q10. Can booleans be used directly as conditions?
Definition: Yes, True/False can be used directly in if conditions.
Example: if is_active:

is_active = True

if is_active:
    print("Active user")

If Q11. What is truthy and falsy evaluation in conditions?
Definition: Non-zero, non-empty objects evaluate as True; empty/zero objects evaluate as False.
Example: if []: is False.

if "":
    print("True")
else:
    print("False")  # empty string is falsy

If Q12. Write a program to check if a number is positive, negative, or zero.
Definition: Multi-conditional branching with if–elif–else.
Example: Standard sign check.

n = int(input("Enter number: "))

if n > 0:
    print("Positive")
elif n < 0:
    print("Negative")
else:
    print("Zero")

Loops Q1. What is a loop in Python? Give a simple example.

Definition: A loop allows repeating a block of code multiple times until a condition is met. It helps automate repetitive tasks efficiently.

Loop TypeUse Case
for loopIterating over sequences
while loopRepeat until condition false
for num in range(3):
    print(num)
Loops Q2. Difference between for loop and while loop?

Definition: A for loop iterates over sequences, while a while loop runs until a condition becomes false.

for loopwhile loop
Fixed number of iterationsUnknown iterations
for i in range(5):
    print(i)

count = 0
while count < 5:
    print(count)
    count += 1
Loops Q3. What does break do inside a loop?

Definition: The break statement immediately stops the loop, even if items remain.

StatementEffect
breakExits loop immediately
for i in range(10):
    if i == 5:
        break
    print(i)
Loops Q4. What does continue do inside a loop?

Definition: continue skips the current iteration and moves to the next.

StatementEffect
continueSkip this iteration
for i in range(5):
    if i == 2:
        continue
    print(i)
Loops Q5. What is the purpose of pass inside loops?

Definition: pass does nothing. It is used as a placeholder inside loops or functions.

KeywordPurpose
passPlaceholder (no action)
for i in range(3):
    pass  # does nothing
Loops Q6. What is a nested loop? Give example.

Definition: A loop inside another loop is called a nested loop, used for matrices or combinations.

Outer LoopInner Loop
Runs 3 timesRuns for each outer iteration
for i in range(3):
    for j in range(2):
        print(i, j)
Loops Q7. What is the purpose of the else block in loops?

Definition: The else part executes only when the loop completes normally without hitting a break. Useful for searching operations where you want to detect β€œnot found”.

Loop Event Else Executes?
Loop ends normally βœ… Yes
Loop breaks early ❌ No
nums = [1, 3, 5, 7]

for n in nums:
    if n == 10:
        break
else:
    print("Number not found")
Loops Q8. How do you loop through a dictionary? Mention two methods.

Definition: Dictionaries can be looped using keys, values, or key–value pairs. Used widely in JSON processing and API data handling.

MethodIterates
dict.keys()Keys only
dict.items()Key + Value
data = {"name": "Hari", "age": 22}

# Method 1
for k in data:
    print(k)

# Method 2
for k, v in data.items():
    print(k, v)
Loops Q9. How do you reverse-iterate a list using a loop?

Definition: Reverse iteration loops backward from last to first. Useful for deleting items safely or scanning data from end.

MethodTechnique
reversed()Recommended way
range()Index-based reverse loop
nums = [1, 2, 3, 4]

# Method 1
for n in reversed(nums):
    print(n)

# Method 2
for i in range(len(nums)-1, -1, -1):
    print(nums[i])
Loops Q10. How do you loop over two lists at the same time?

Definition: Use zip() to pair elements from two lists. Mostly used in ML (features + labels pairing).

FunctionPurpose
zip()Combines multiple iterables
names = ["A", "B"]
scores = [90, 85]

for name, score in zip(names, scores):
    print(name, score)
Loops Q11. What is the difference between enumerate() and a normal loop?

Definition: enumerate() returns index + value together. Useful when looping lists while tracking positions.

Loop TypeWhat You Get
Normal LoopValue only
enumerateIndex + Value
items = ["pen", "book"]

for i, item in enumerate(items):
    print(i, item)
Loops Q12. How to generate all pairs using loops (Cartesian product)?

Definition: Nested loops can generate every combination between two lists. Useful in ML grid search, coordinate generation, pair matching.

Input ListsOutput
[1,2], ['a','b'](1,a), (1,b), (2,a), (2,b)
nums = [1, 2]
chars = ["a", "b"]

for n in nums:
    for c in chars:
        print((n, c))
Functions Q1. What is a function in Python?

Definition: A function is a reusable block of code that performs a specific task. Functions help avoid repetition and improve modularity in programs.

PartMeaning
defStarts a function
returnSends back a value
def greet():
    return "Hello"

print(greet())
Functions Q2. What are parameters and arguments?

Definition: Parameters are variables in function definition; arguments are actual values passed during calling. Functions use parameters to receive dynamic input.

TermRole
ParameterPlaceholder variable
ArgumentValue passed
def add(a, b):  # a, b = parameters
    return a + b

print(add(5, 3))   # 5,3 = arguments
Functions Q3. What is the use of return statement?

Definition: return sends a result back to the caller and ends the function immediately. It is essential for passing output to other parts of the program.

FeatureExplanation
Stops functionCode after return won’t run
Sends valueOutput available to caller
def multiply(a, b):
    return a * b
Functions Q4. What are default parameters? Why useful?

Definition: Default parameters provide a fallback value when no argument is passed. Useful for optional behaviors or flexible function calls.

Parameter TypeBehavior
DefaultProvides backup value
def greet(name="Guest"):
    print("Hello", name)

greet()
greet("Hari")
Functions Q5. What are *args and **kwargs?

Definition: *args accepts unlimited positional arguments; **kwargs accepts unlimited keyword arguments. Useful for flexible function calls.

SyntaxMeaning
*argsTuple of values
**kwargsDictionary of key-values
def demo(*args, **kwargs):
    print(args)
    print(kwargs)

demo(1,2, name="Hari")
Functions Q6. What is recursion? Give example.

Definition: Recursion is when a function calls itself to solve smaller subproblems. Used heavily in DSA: trees, graphs, factorial, fibonacci.

PartRole
Base CaseStops recursion
Recursive CaseCalls itself
def fact(n):
    if n == 1:
        return 1
    return n * fact(n-1)
Functions Q7. What is a lambda function? How different from normal function?

Definition: A lambda is a small one-line anonymous function. Used in sorting, filtering, map, reduce operations.

TypeFeature
lambdaOne-line, anonymous
defMulti-line, named
square = lambda x: x*x
print(square(5))
Functions Q8. What is scope? Explain local vs global variables.

Definition: Scope decides where a variable can be accessed. Local exists inside function; global exists everywhere.

TypeAccess Level
localInside function only
globalEntire program
x = 10  # global

def test():
    x = 5   # local
    print(x)
Functions Q9. What is function annotation (type hinting)?

Definition: Type hints indicate expected data types for parameters and return values. They don’t enforce types but help documentation and debugging.

FormatPurpose
a: intParameter hint
-> intReturn hint
def add(a: int, b: int) -> int:
    return a + b
Functions Q10. Can a function return multiple values?

Definition: Yes, Python functions can return multiple values as a tuple. Helpful when functions compute multiple results at once.

FeatureExplanation
Multiple returnPacked into tuple
def stats(a, b):
    return a+b, a*b

print(stats(3,4))
Functions Q11. What are docstrings and how to write them?

Definition: Docstrings describe what a function does, how to use it, and what it returns. They appear when using help() or in documentation tools.

PartDescription
"""..."""Defines docstring
def greet():
    """This function prints greeting message"""
    print("Hello")
Functions Q12. What is a higher-order function?

Definition: A higher-order function accepts another function as argument or returns one. Used in map, filter, decorators, and functional programming.

FeatureExplanation
Takes functionLike map(func, list)
Returns functionUsed in decorators
def apply(func, x):
    return func(x)

print(apply(lambda n: n+n, 5))
Lambda Q1. What is a lambda function in Python?

Definition: A lambda function is a small anonymous one-line function created using the lambda keyword. It is mainly used in sorting, filtering, and functional programming.

FeatureMeaning
AnonymousNo function name
Single expressionCannot contain multiple statements
square = lambda x: x * x
print(square(6))
Lambda Q2. How are lambda functions different from normal functions?

Definition: Normal functions use def and support multiple statements, whereas lambda functions are restricted to one line and do not require a name.

Normal FunctionLambda Function
Multi-line allowedOne-line only
Has a nameAnonymous
def add(a, b):
    return a + b

add2 = lambda a, b: a + b
Lambda Q3. How do lambda functions work with map()?

Definition: map() applies a lambda function to each element of an iterable and produces a new transformed iterable.

FunctionPurpose
map(func, iterable)Transforms each item
nums = [1,2,3,4]
doubled = list(map(lambda x: x*2, nums))
print(doubled)
Lambda Q4. How do lambda functions work with filter()?

Definition: filter() selects elements based on a boolean condition defined inside a lambda expression.

filter()Purpose
filter(func, iterable)Keeps items that return True
nums = [1,2,3,4,5,6]
evens = list(filter(lambda x: x%2 == 0, nums))
print(evens)
Lambda Q5. What is a list comprehension?

Definition: List comprehension provides a concise syntax to generate a new list from an iterable using a single readable line.

FormatExample
[expr for item in list] [x*x for x in nums]
squares = [x*x for x in range(6)]
print(squares)
Lambda Q6. How do conditional expressions work inside list comprehensions?

Definition: List comprehensions can contain inline if statements to filter or conditionally generate values.

TypeExample
With filter[x for x in nums if x%2==0]
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
Lambda Q7. What is a dictionary comprehension? Give an example.

Definition: Dictionary comprehension lets you generate dictionaries using a clear and Pythonic one-line syntax.

FormatExample
{k:v for item} {x: x*x for x in nums}
squares = {x: x*x for x in range(5)}
print(squares)
Lambda Q8. What is a set comprehension? How is it different from list comprehension?

Definition: A set comprehension creates a set using one-line syntax. Unlike lists, sets automatically remove duplicates.

ComprehensionUnique?
ListNo
SetYes
unique_vals = {x % 3 for x in range(10)}
print(unique_vals)
Lambda Q9. What is a generator expression? How is it different from list comprehension?

Definition: A generator expression produces values lazily on demand instead of storing all values in memory like list comprehensions.

TypeMemory Usage
List comprehensionStores entire list
Generator expressionGenerates item-by-item
gen = (x*x for x in range(5))
print(next(gen))
Lambda Q10. How do nested comprehensions work? Give example.

Definition: Nested comprehensions contain multiple for loops inside a single comprehension, commonly used for matrix flattening or pair generation.

Use CaseExample
Flatten list[y for x in matrix for y in x]
matrix = [[1,2],[3,4]]
flat = [y for x in matrix for y in x]
print(flat)
Lambda Q11. Can we use multiple conditions inside comprehensions?

Definition: Yes, comprehensions allow multiple if clauses to finely filter elements based on multiple conditions.

FeatureMeaning
Multiple filtersx>0 and x%2==0
nums = range(20)
result = [x for x in nums if x > 5 if x % 2 == 0]
print(result)
Lambda Q12. What are the advantages of comprehensions over loops?

Definition: Comprehensions are faster, more readable, and more Pythonic than traditional loops for data transformation tasks.

AdvantageReason
SpeedOptimized internally
Cleaner CodeOne-line syntax
result1 = []
for x in range(10):
    result1.append(x*x)

result2 = [x*x for x in range(10)]
Exceptions Q1. What is an exception in Python? Why do exceptions occur?

Definition:
An exception is a runtime error that interrupts normal program flow and stops execution unless handled. Exceptions occur when invalid operations happen such as dividing by zero, accessing missing keys, or using wrong types.

Cause Example
Invalid operation 10/0
Wrong type "a" - 3
print(10/0)  # ZeroDivisionError
Exceptions Q2. What is a try–except block and why do we use it?

Definition:
A try–except block lets you safely run risky code and handle errors gracefully without crashing the program. It improves stability and user experience by replacing crashes with meaningful messages.

Block Purpose
try Risky code
except Handles error
try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
Exceptions Q3. What are else and finally blocks? When should you use them?

Definition:
The else block runs only when no exceptions occur, helping separate normal logic from error logic. The finally block always executes, useful for cleanup tasks like closing files or database connections.

Block When it runs
else If no error
finally Always runs
try:
    val = int("10")
except ValueError:
    print("Invalid number")
else:
    print("Converted:", val)
finally:
    print("Done")
Exceptions Q4. What is an exception object and how does it propagate?

Definition:
An exception object stores error details and moves up the call stack when raised until handled by a matching except block. If unhandled at all levels, the program terminates with a traceback.

Stage Meaning
Raised Error created
Propagation Moves upward
def level1(): return level2()
def level2(): return level3()
def level3(): raise ValueError("Error happened")

try:
    level1()
except ValueError as e:
    print("Handled:", e)
Exceptions Q5. What is multiple except handling? Why is order important?

Definition:
Multiple except blocks let you handle different error types using separate logic. Order matters because Python checks them top-to-bottom and the first matching except executes.

PositionMeaning
TopMost specific exceptions
BottomGeneral exceptions
try:
    x = int("abc")
except ValueError:
    print("Invalid conversion")
except Exception:
    print("General error")
Exceptions Q6. What is exception chaining and how does raise ... from work?

Definition:
Exception chaining links a new exception with the original one so developers can track the full error sequence. The raise new_error from old_error syntax explicitly connects both errors.

FeatureBenefit
Chained exceptionsComplete error history
from keywordSpecifies underlying cause
try:
    int("xyz")
except ValueError as e:
    raise RuntimeError("Conversion failed") from e
Exceptions Q7. What is the difference between SyntaxError and RuntimeError?

Definition:
A SyntaxError occurs before program execution, caused by invalid Python grammar. RuntimeError occurs during execution due to unexpected conditions in the logic.

Error TypeOccurs When
SyntaxErrorBefore execution
RuntimeErrorDuring execution
# SyntaxError example (won't run)
# if True print("Hello")

# RuntimeError example
def f():
    return f()
# f()  # RecursionError
Exceptions Q8. Why is broad except dangerous? What is best practice?

Definition:
A broad except: catches every error and hides real bugs, making debugging extremely difficult. Best practice is to handle specific exceptions and use general except only with strong justification.

Bad PracticeGood Practice
except: except ValueError, TypeError…
try:
    x = int("abc")
except:
    print("Bad: hides real issues")

try:
    x = int("abc")
except ValueError:
    print("Good: proper error handling")
Exceptions Q9. What is raising exceptions manually? When should you use raise?

Definition:
Manual raising lets developers trigger errors intentionally when invalid inputs or states are detected. Use raise when you want to enforce rules or stop execution with a clear message.

Use CaseWhy
Input validation Protect program
Stop execution early Prevent damage
def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

set_age(-1)
Exceptions Q10. How do custom exceptions work? Why create your own exception class?

Definition:
Custom exceptions allow you to define project-specific error types, improving clarity and debugging. They inherit from Exception and contain meaningful messages relevant to your application.

BenefitMeaning
Readable errors Clear intent
Better grouping Handle project-specific failures
class NegativeBalanceError(Exception):
    pass

def withdraw(amount):
    if amount < 0:
        raise NegativeBalanceError("Cannot withdraw negative amount")

withdraw(-100)
Exceptions Q11. What is context management in exception handling?

Definition:
Context managers automate setup and cleanup of resources using __enter__ and __exit__. They ensure resources are released even if exceptions occur inside the managed block.

MethodPurpose
__enter__ Setup
__exit__ Cleanup
with open("file.txt") as f:
    data = f.read()  # file closes even if error occurs
Exceptions Q12. How does Python’s exception hierarchy work? What is BaseException?

Definition:
Python exceptions follow a hierarchy where BaseException is the root for all error types. Understanding this structure helps catch errors accurately without over-catching.

ClassLevel
BaseExceptionRoot
ExceptionGeneral errors
ValueError, TypeError…Specific
try:
    value = int("Hari")
except Exception as e:
    print(type(e))
File Handling Β· Q1
How do you open and read the full content of a text file in Python?
Basic open() usage, read entire file into a string.

Theory: To read a text file, you use open("filename", "r"), which returns a file object. Calling .read() on it loads the entire content as a single string.

Step Description Example
1 Open file in read mode open("notes.txt", "r")
2 Read entire content f.read()
3 Close file (if no with) f.close()
# Practical: Read full file content
file_path = "notes.txt"

f = open(file_path, "r")  # open in read mode
content = f.read()                     # entire file as single string
f.close()                                   # close file

print(content)
File Handling Β· Q2
Explain common file modes in Python ("r", "w", "a", "rb", "wb") with an example.
Understand how different modes control reading/writing behaviour.

Theory: File modes decide how you interact with a file. Read mode expects file to exist, write mode overwrites existing content, and append mode adds data to the end. Binary modes ("rb"/"wb") are used for non-text files like images.

Mode Meaning Typical Use
"r" Read text (file must exist) Config, log reading
"w" Write text, truncate file Generate reports
"a" Append text at end Append new logs
"rb" Read binary Images, PDFs
"wb" Write binary (truncate) Save downloaded files
# Practical: Demonstrate different modes

# 1) Write text file (overwrites if exists)
with open("report.txt", "w") as f:
    f.write("First line\n")

# 2) Append a new line
with open("report.txt", "a") as f:
    f.write("Appended line\n")

# 3) Read file back
with open("report.txt", "r") as f:
    print(f.read())
File Handling Β· Q3
What is a context manager (with open(...)) and why is it preferred over manual open()/close()?
Automatic resource management and exception safety using with.

Theory: A context manager ensures that resources are properly acquired and released. When using with open(...), the file is automatically closed even if an exception occurs, which prevents resource leaks and simplifies code.

Approach Risk Auto-close?
f = open(...); f.close() If exception occurs before close(), file may remain open. ❌ No
with open(...) Safely handles errors. βœ… Yes
# Practical: Using context manager for safe file handling

file_path = "users.txt"

with open(file_path, "r", encoding="utf-8") as f:
    # Inside this block the file is open
    for line in f:
        print(line.strip())

# Outside the with-block, f is automatically closed.
File Handling Β· Q4
Difference between read(), readline(), and readlines() with an example.
Choosing the right method for full file, single line, or list of lines.

Theory: All three methods read data from an open file object, but they differ in how much they read: entire content, one line at a time, or all lines as a list.

Method Returns Use case
read() One big string Small files
readline() Next line (with \n) Process line by line manually
readlines() List of all lines Small/medium files as list
# Practical: Compare read, readline, readlines

with open("sample.txt", "r") as f:
    full = f.read()
print("Using read():", repr(full))

with open("sample.txt", "r") as f:
    line1 = f.readline()
    line2 = f.readline()
print("Using readline():", repr(line1), repr(line2))

with open("sample.txt", "r") as f:
    all_lines = f.readlines()
print("Using readlines():", all_lines)
File Handling Β· Q5
How do you write multiple lines of text to a file and then read them back?
Using write() / writelines() and verifying by reading.

Theory: Writing can be done line by line with write() or in bulk using writelines(). Always include newline characters \n yourself because these functions don’t add them automatically.

Function Input Type Automatic newline?
write() Single string No
writelines() Iterable of strings No
# Practical: Write and read multiple lines

lines = [
    "Line 1: Hello\n",
    "Line 2: File handling\n",
    "Line 3: Python\n",
]

# Write lines
with open("multi_lines.txt", "w") as f:
    f.writelines(lines)

# Read lines back
with open("multi_lines.txt", "r") as f:
    for line in f:
        print(line.strip())
File Handling Β· Q6
How do you safely build file paths and check if a file exists before opening it?
Cross-platform paths using os.path or pathlib.

Theory: Instead of hardcoding paths with "\" or "/", use os.path.join() or pathlib.Path to build platform-independent paths. Always check existence to avoid FileNotFoundError.

Module Functionality Example
os.path Join paths, check existence os.path.exists(path)
pathlib Object-oriented paths Path("data") / "file.txt"
import os
from pathlib import Path

# Using os.path
base_dir = "data"
file_name = "input.txt"
file_path = os.path.join(base_dir, file_name)

if os.path.exists(file_path):
    with open(file_path, "r") as f:
        print(f.readline().strip())
else:
    print("File not found:", file_path)

# Using pathlib
p = Path("data") / "input.txt"
if p.exists():
    print(p.read_text(encoding="utf-8"))
File Handling Β· Q7
How do you handle FileNotFoundError while opening a file and show a user-friendly message?
Combining exception handling with file operations for robust code.

Theory: When a file is missing, open() in read mode raises FileNotFoundError. You should wrap the operation inside a try/except block and log or display a clear message instead of crashing the program.

Component Role Example
try Wrap risky file operation open("config.txt")
except FileNotFoundError Handle missing file gracefully Log or print message
file_name = "config.txt"

try:
    with open(file_name, "r") as f:
        data = f.read()
        print("File content:", data)
except FileNotFoundError:
    print(f"Error: {file_name} not found. Please check the path.")
File Handling Β· Q8
How do you read a very large file efficiently without loading it entirely into memory?
Iterating line by line or using chunks for memory efficiency.

Theory: For large files, avoid read() or readlines() because they load everything into RAM. Instead, iterate over the file object line by line or read fixed-size chunks.

Technique Memory usage Example
Line iteration Low for line in f
Chunk read Configurable f.read(4096)
# Practical: Count lines in a huge file

line_count = 0
with open("huge_log.txt", "r", encoding="utf-8", errors="ignore") as f:
    for _ in f:
        line_count += 1

print("Total lines =", line_count)
File Handling Β· Q9
How do you read and write CSV files in Python using the csv module?
Structured data handling for rows and columns.

Theory: CSV (Comma-Separated Values) files store tabular data. The csv module provides reader and writer objects to work row by row, avoiding manual splitting on commas.

Class Purpose Example
csv.writer Write rows writer.writerow([...])
csv.reader Read rows for row in reader
import csv

# Write CSV
rows = [
    ["name", "age"],
    ["Hari", 22],
    ["Vinay", 23],
]

with open("users.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(rows)

# Read CSV
with open("users.csv", "r", newline="") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
File Handling Β· Q10
How do you read and write JSON files in Python using the json module?
Serializing and deserializing Python objects to JSON.

Theory: JSON is a standard text format used for APIs and configuration. Use json.dump() / json.load() with file objects to save and load structured data like dicts and lists.

Function Direction Input/Output
json.dump() Python β†’ JSON file (obj, file)
json.load() JSON file β†’ Python (file)
import json

user = {
    "name": "Hari",
    "skills": ["Python", "Pandas"],
    "active": True
}

# Write JSON
with open("user.json", "w") as f:
    json.dump(user, f, indent=4)

# Read JSON
with open("user.json", "r") as f:
    loaded = json.load(f)

print(loaded["name"], loaded["skills"])
File Handling Β· Q11
How do you copy a binary file (e.g., image) using Python file handling?
Using binary modes "rb" and "wb" to copy raw bytes.

Theory: For non-text files, always use binary modes. This ensures bytes are not decoded or modified by newline conversion. You can read entire content or stream in chunks.

Mode Used For Example
"rb" Read binary source open("img.png","rb")
"wb" Write binary target open("copy.png","wb")
# Practical: Copy image file (binary)

src = "logo.png"
dst = "logo_copy.png"

with open(src, "rb") as f_src, \
     open(dst, "wb") as f_dst:
    for chunk in iter(lambda: f_src.read(4096), b""):
        f_dst.write(chunk)

print("Copied to", dst)
File Handling Β· Q12
What are some best practices for log file handling in Python? Show a simple log append example.
Using append mode, timestamps, and safe writing patterns.

Theory: For logs, you typically open files in append mode, include timestamps, and avoid rewriting the whole file. For larger apps, use the logging module, but for small scripts simple manual logging can be enough.

Best Practice Reason
Use append mode "a" Don’t lose old logs
Add timestamp per line Helps debugging & tracing
Use with context manager Ensure file closes properly
from datetime import datetime

def log_message(message, file_name="app.log"):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    line = f"[{timestamp}] {message}\n"
    with open(file_name, "a", encoding="utf-8") as f:
        f.write(line)

# Practical: Write some logs
log_message("Application started")
log_message("User logged in")
OOP Β· Q1
What is OOP and why is it used?
Organizing code using objects & classes

Theory: Object-Oriented Programming allows grouping related data (attributes) and functions (methods) inside reusable structures called classes. OOP improves code organization, modularity, readability, and real-world mapping.

Benefit Meaning
Modularity Code is divided into logical units
Reusability Classes can be reused many times
# Practical OOP example
class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print(f"Hello, I am {self.name}")

p = Person("Vinay")
p.greet()
OOP Β· Q2
What are classes and objects?
Blueprint vs instance

Theory: A class is a blueprint defining structure and behavior. An object is an instance created from that class with real data loaded into attributes.

Term Meaning
Class Design or template
Object Real-world usable instance
class Car:
    def __init__(self, brand):
        self.brand = brand

my_car = Car("Tesla")
print(my_car.brand)
OOP Β· Q3
What are instance variables and class variables?
Difference in memory usage & scope

Theory: Instance variables belong to a specific object. Class variables are shared across all objects created from the class.

Type Stored Where? Shared?
Instance variable Inside object ❌ No
Class variable Inside class βœ… Yes
class Student:
    college = "TEKS"   # class variable

    def __init__(self, name):
        self.name = name         # instance variable

s1 = Student("Hari")
s2 = Student("Vinay")

print(s1.college, s2.college)
OOP Β· Q4
What is the purpose of the __init__() method?
Constructor in Python

Theory: __init__() is automatically called when an object is created. It initializes the object's attributes and prepares the object for use.

Feature Explanation
Auto-calls Runs automatically after object creation
Used to initialize Sets initial values for attributes
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

e = Employee("Raj", 50000)
print(e.name, e.salary)
OOP Β· Q5
What is encapsulation?
Data hiding using private variables

Theory: Encapsulation restricts direct access to class data by using private attributes (__variable) and exposes controlled access via getter/setter methods.

Concept Explanation
Private variable __price β†’ cannot be accessed directly
Getter Reads private data safely
class Product:
    def __init__(self, price):
        self.__price = price

    def get_price(self):
        return self.__price

p = Product(999)
print(p.get_price())
OOP Β· Q6
What is inheritance in Python?
Reusing parent class features

Inheritance allows a class to acquire attributes and methods of another class, reducing duplication and improving code reuse.

Type Meaning
Single Child inherits one parent
Multiple Child inherits multiple parents
class Animal:
    def speak(self):
        print("General sound")

class Dog(Animal):
    def speak(self):
        print("Bark")

Dog().speak()
OOP Β· Q7
What is polymorphism?
Same interface, different behavior

Polymorphism allows the same method call to behave differently depending on the object's class.

Form Example
Method overriding Child redefines parent method
Duck typing Object’s behavior matters, not type
class Cat:
    def sound(self):
        print("Meow")

class Dog:
    def sound(self):
        print("Bark")

for animal in [Cat(), Dog()]:
    animal.sound()
OOP Β· Q8
What is abstraction?
Hiding internal details

Abstraction hides internal implementation and exposes only essential features.

Aspect Meaning
User sees Simple interface
System hides Complex logic
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Square(Shape):
    def area(self):
        print(4 * 4)

Square().area()
OOP Β· Q9
What is method overriding?
Child provides new implementation

Method overriding occurs when a child class redefines a method already defined in its parent class.

Parent Child
Defines basic method Gives new behavior
class A:
    def show(self):
        print("Parent show")

class B(A):
    def show(self):
        print("Child show")

B().show()
OOP Β· Q10
What does super() do?
Calls parent methods

super() gives access to parent class methods without using the parent class name explicitly.

Use Benefit
Call parent constructor Avoids rewriting code
class A:
    def __init__(self):
        print("A init")

class B(A):
    def __init__(self):
        super().__init__()
        print("B init")

B()
OOP Β· Q11
What is MRO in Python?
Order of method lookup

MRO (Method Resolution Order) determines the order in which Python searches classes for methods during inheritance.

Order Meaning
C3 Linearization Algorithm to order parent classes
class A: pass
class B(A): pass
class C(B): pass

print(C.mro())
OOP Β· Q12
What are dunder methods?
Special methods starting with __

Dunder methods (double-underscore methods) allow operator overloading, object printing, iteration, comparisons etc.

Method Purpose
__str__ User-friendly print
__add__ Operator overloading
class Book:
    def __str__(self):
        return "Book Object"

print(Book())
Iterators Β· Q1
What is an iterator in Python?
Object that returns data one element at a time

An iterator is an object that implements __iter__() and __next__(), allowing sequential access to items.

Method Purpose
__iter__() Returns iterator object
__next__() Returns next value
nums = iter([1, 2, 3])
print(next(nums))
print(next(nums))
Iterators Β· Q2
What is the difference between Iterable and Iterator?
iter() converts iterable β†’ iterator

An iterable contains multiple values (list, tuple) but does not produce items one by one. An iterator produces items sequentially using __next__().

Iterable Iterator
Has __iter__() Has __next__()
e.g., list, tuple Created using iter()
lst = [1,2,3]
it = iter(lst)
print(next(it))
Iterators Β· Q3
How do you create a custom iterator?
Implement __iter__ and __next__

A custom iterator is created by defining a class that implements __iter__() and __next__().

Method Role
__iter__() Returns self
__next__() Returns next element or raises StopIteration
class Counter:
    def __init__(self):
        self.num = 1
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.num <= 3:
            val = self.num
            self.num += 1
            return val
        raise StopIteration

for i in Counter():
    print(i)
Iterators Β· Q4
What is a generator?
Function that uses yield

A generator is a special function that returns an iterator and produces values lazily using yield.

Feature Benefit
Lazy evaluation Saves memory
Maintains state Continues from last yield
def gen():
    yield 1
    yield 2
    yield 3

for x in gen():
    print(x)
Iterators Β· Q5
What is the difference between yield and return?
return ends, yield pauses

return terminates the function immediately. yield pauses the function and resumes on next call.

return yield
Ends function Pauses & resumes
Normal value Generator value
def f():
    return 10

def g():
    yield 10
    yield 20
Iterators Β· Q6
Generator vs List β€” which is faster?
Generators = memory efficient

Generators are faster for large datasets because they generate values on demand instead of storing all values in memory.

List Generator
Stores entire data Yields one value at a time
High memory usage Low memory usage
lst = [x for x in range(1000000)]      # Heavy
gen = (x for x in range(1000000))      # Light
Iterators Β· Q7
What is send() in generators?
Send value back to generator

send() resumes the generator and sends a value inside the paused yield.

Function Use
send(value) Injects data into generator
def demo():
    x = yield "start"
    yield x * 10

g = demo()
print(next(g))
print(g.send(5))
Iterators Β· Q8
What does yield from do?
Delegates to another generator

yield from allows a generator to delegate part of its operations to another generator or iterable.

Benefit Meaning
Cleaner code No nested loops
def outer():
    yield from [1,2,3]
    yield 4

for i in outer():
    print(i)
Iterators Β· Q9
What are generator expressions?
Lazy version of list comprehension

Generator expressions look similar to list comprehensions but use parentheses and generate elements lazily.

List Comp Generator Expr
[x*x for x in range(5)] (x*x for x in range(5))
gen = (x*x for x in range(3))
print(next(gen))
Iterators Β· Q10
What is StopIteration?
Signals end of iteration

StopIteration is raised by iterators to signal that no more items are available.

Where raised? Meaning
__next__() Iteration completed
it = iter([1])
print(next(it))
# next(it) -> raises StopIteration
Iterators Β· Q11
Can a generator be infinite?
Yes, generators support infinite streams

Yes, because generators compute values lazily, they can generate infinite sequences without memory issues.

Feature Benefit
Lazy execution Infinite is possible
def infinite():
    n = 1
    while True:
        yield n
        n += 1
Iterators Β· Q12
Real-world use cases of generators?
Streaming, pipelines, large files

Generators are widely used when handling big data, file streaming, pipelines, or infinite sequences.

Use Case Why Generator?
Reading large files Loads one line at a time
ETL pipelines Generates data step-by-step
def read_large_file():
    with open("big.txt") as f:
        for line in f:
            yield line
Decorators Β· Q1
What is a decorator in Python?
Decorator modifies behavior of a function

A decorator is a function that wraps another function to extend or modify its behavior without changing the original function's code.

Feature Meaning
Reusability Wrap logic for multiple functions
Non-intrusive No change in original code
def my_decorator(func):
    def wrapper():
        print("Before")
        func()
        print("After")
    return wrapper

@my_decorator
def greet():
    print("Hello!")

greet()
Decorators Β· Q2
How does Python internally apply a decorator?
Decorator replaces function with wrapper

When Python sees @decorator, it passes the function below it as an argument to the decorator and replaces it with the returned wrapper.

Before Decoration After Decoration
f = function f = decorator(function)
@deco
def hello():
    print("Hi")

# Same as:
hello = deco(hello)
Decorators Β· Q3
How do you write a decorator that accepts arguments?
Use 3-level nested functions

A decorator that accepts arguments requires a wrapper around the decorator itself β€” making it a three-layer function.

Layer Purpose
Outer function Accept decorator arguments
Decorator function Accept target function
Wrapper Execute logic
def repeat(n):
    def decorator(func):
        def wrapper():
            for _ in range(n):
                func()
        return wrapper
    return decorator

@repeat(3)
def hello():
    print("Hi")
Decorators Β· Q4
What is functools.wraps and why is it important?
Preserves function metadata

functools.wraps copies metadata (__name__, __doc__) from the original function to the wrapper, keeping introspection accurate.

Without wraps() With wraps()
Loses name, docstring Preserves metadata
from functools import wraps

def deco(func):
    @wraps(func)
    def wrapper():
        return func()
    return wrapper
Decorators Β· Q5
How do multiple decorators work?
Applied bottom β†’ top stacking

Decorators are applied from bottom to top, meaning the closest decorator executes first.

Order Execution
@A Second
@B First
@A
@B
def f():
    pass
Decorators Β· Q6
What is a class decorator?
Decorator that wraps a class

A class decorator accepts a class instead of a function and returns a modified class.

Target Effect
Class Wraps behavior or injects attributes
def decorate(cls):
    cls.tag = "decorated"
    return cls

@decorate
class Test:
    pass
Decorators Β· Q7
How do you decorate a function with parameters?
Wrapper must accept *args/**kwargs

The wrapper must accept variable arguments so it can decorate any function regardless of parameters.

Parameter type Purpose
*args Positional arguments
**kwargs Keyword arguments
def deco(func):
    def wrapper(*args, **kwargs):
        print("Before")
        return func(*args, **kwargs)
    return wrapper
Decorators Β· Q8
Write a simple logging decorator.
Logs before calling function

A logging decorator prints information before executing a function.

Log Type Purpose
Function name Debugging
Parameters Tracking values
def log(func):
    def wrapper(*args, **kwargs):
        print("Calling", func.__name__)
        return func(*args, **kwargs)
    return wrapper
Decorators Β· Q9
Write a decorator to measure execution time.
Use time.time()

A time decorator calculates function execution duration using time.time().

Step Action
Start Record time
End Print duration
import time

def timer(func):
    def wrapper(*args, **kwargs):
        s = time.time()
        result = func(*args, **kwargs)
        print("Time:", time.time() - s)
        return result
    return wrapper
Decorators Β· Q10
Explain decorator order with an example.
Bottom-most decorator applies first

The decorator closest to the function wraps it first, and then outer decorators wrap the result.

Decorator Execution Order
@A Second
@B First
@A
@B
def f():
    pass
Decorators Β· Q11
What are real-world use cases of decorators?
Authentication, caching, logging…

Decorators are widely used for modifying function behavior in frameworks and large systems.

Use Case Purpose
Logging Tracking function calls
Authentication Verify access rights
Caching Improve performance
@login_required
def dashboard():
    pass
Decorators Β· Q12
How does a decorator return values?
Wrapper returns function output

A decorator’s wrapper should return the inner function’s value so the decorated function works normally.

Requirement Meaning
Return value Preserves function output
def deco(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return result
    return wrapper
Memory Β· Q1
What is memory management in Python?
Python manages memory automatically using private heap

Python memory management refers to how Python allocates, stores, and frees memory during program execution using its built-in private heap space.

Component Role
Private Heap Stores all Python objects
Memory Manager Allocates memory automatically
x = 10   # Stored in Python heap
Memory Β· Q2
What is reference counting?
Primary technique to track object usage

Reference counting is a mechanism where Python keeps track of how many references point to an object. When the count drops to 0 β†’ the memory is freed.

Action Effect
x = obj Count +1
del x Count –1
import sys
a = [1,2,3]
print(sys.getrefcount(a))
Memory Β· Q3
What is garbage collection?
Reclaims memory of unused objects

Python’s garbage collector removes unreachable objects β€” especially those involved in **circular references**.

Collector Role
Gen 0 Short-lived objects
Gen 1 & 2 Long-lived objects
import gc
gc.collect()
Memory Β· Q4
What is a memory leak in Python?
Memory not released when unused

A memory leak occurs when Python objects are no longer needed but are not garbage-collected (often due to circular references or global variables).

Reason Example
Circular references Objects pointing to each other
Uncleared cache Large list stored globally
a = []
b = [a]
a.append(b)   # circular reference
Memory Β· Q5
What are circular references?
Objects referencing each other

Two or more objects reference each other, preventing their reference counts from reaching zero and causing memory leaks.

Object A Object B
Points to B Points to A
class A:
    pass

a1 = A()
a2 = A()
a1.ref = a2
a2.ref = a1   # circular
Memory Β· Q6
What is PyMalloc?
Python’s memory allocator for small objects

PyMalloc is Python’s specialized memory allocator designed to efficiently manage small memory blocks (≀ 512 bytes).

Size Allocation Method
Small objects PyMalloc
Large objects System malloc()
x = 42  # Allocated via PyMalloc
Memory Β· Q7
How to analyze memory usage in Python?
Use memory_profiler and tracemalloc

Python offers tools like memory_profiler and tracemalloc to analyze memory consumption line-by-line.

Tool Purpose
memory_profiler Line-by-line memory report
tracemalloc Tracks memory allocations
import tracemalloc
tracemalloc.start()
Memory Β· Q8
Difference between shallow copy and deep copy.
Deep copy duplicates nested objects

Shallow copy creates a new object but copies references. Deep copy creates entirely new nested objects.

Copy Type Effect
Shallow Shares inner objects
Deep Copies all nested objects
import copy
a = [[1,2]]
b = copy.deepcopy(a)
Memory Β· Q9
What is memory fragmentation?
Free space scattered β†’ inefficient usage

Memory fragmentation occurs when free memory is divided into small blocks, making it hard to allocate large continuous sections.

Type Meaning
Internal Unused space inside blocks
External Free space is scattered
# Python avoids fragmentation using memory pools
Memory Β· Q10
Difference between stack and heap memory.
Stack stores function frames, heap stores objects
Stack Heap
Stores function calls Stores Python objects
Fast Slightly slower
def f():
    x = 10   # x in stack, value in heap
Memory Β· Q11
Why doesn’t Python free memory immediately?
Python uses memory pools for performance

Python holds memory blocks in pools for future reuse instead of releasing them back to the OS immediately. This improves performance and reduces fragmentation.

Reason Benefit
Pool allocator Faster reuse
Avoid fragmentation Efficient memory layout
# Python memory is reused internally
Memory Β· Q12
What are best practices to reduce memory usage?
Use generators, del, small structures
Technique Why it helps
Use generators Lowers memory footprint
del unused vars Reduces reference count
Use tuples instead of lists Immutables use less memory
def read_large():
    for line in open("big.txt"):
        yield line   # generator saves memory
Coding Q1. Write a program to find the sum of all elements in a list.

Definition: Summing list values is a basic aggregation operation used in many algorithms and data transformations.

Input Output
[2, 5, 7] 14
nums = [2, 5, 7]
total = sum(nums)
print(total)
Coding Q2. Write a Python program to count vowels in a string.

Definition: Vowel counting is a common string-processing task used in pattern recognition and text analysis.

s = "Interview"
vowels = "aeiou"
count = sum(1 for ch in s.lower() if ch in vowels)
print(count)
Coding Q3. Reverse a string without using slicing.

Definition: Reversing a string manually demonstrates loop usage and iteration logic.

s = "Python"
rev = ""
for ch in s:
    rev = ch + rev
print(rev)
Coding Q4. Write a program to find the maximum element in a list without using max().

Definition: Maximum finding is core logic in selection algorithms.

nums = [4, 8, 2, 9, 1]
mx = nums[0]
for n in nums:
    if n > mx:
        mx = n
print(mx)
Coding Q5. Check whether a number is prime or not.

Definition: Prime number logic is widely used in hashing and modular arithmetic.

n = 13
is_prime = True

if n < 2:
    is_prime = False
else:
    for i in range(2, int(n**0.5)+1):
        if n % i == 0:
            is_prime = False
            break

print(is_prime)
Coding Q6. Write a program to count words in a sentence.

Definition: Word tokenization is important in NLP and preprocessing tasks.

s = "Python is easy to learn"
count = len(s.split())
print(count)
Coding Q7. Remove duplicates from a list and keep the original order.

Definition: Order-preserving duplicate removal is applied in data cleaning pipelines.

nums = [1,2,2,3,1,4]
seen = set()
unique = []

for n in nums:
    if n not in seen:
        seen.add(n)
        unique.append(n)

print(unique)
Coding Q8. Write a program to check if a string is a palindrome.

Definition: Palindrome logic is used in pattern recognition and text classification.

s = "Madam"
s2 = s.lower()
print(s2 == s2[::-1])
Coding Q9. Find the factorial of a number using a loop.

Definition: Factorial math is used in combinatorics and probability calculations.

n = 5
fact = 1
for i in range(1, n+1):
    fact *= i
print(fact)
Coding Q10. Count occurrences of each character in a string.

Definition: Frequency counting is fundamental in hashing and compression algorithms.

s = "programming"
freq = {}

for ch in s:
    freq[ch] = freq.get(ch, 0) + 1

print(freq)
Coding Q11. Write a Python program to find the smallest number in a list without using min().

Definition: Finding the minimum value manually teaches comparison logic and linear scanning used in basic algorithms.

nums = [5, 2, 9, 1, 7]
mn = nums[0]

for n in nums:
    if n < mn:
        mn = n

print(mn)
Coding Q12. Write a program to remove all spaces from a string.

Definition: Space removal is commonly used in text preprocessing and user-input cleaning.

s = "Python is fun"
result = s.replace(" ", "")
print(result)
Coding Q13. Write a Python program to check if a number is even or odd.

Definition: Even–odd classification is a simple arithmetic check used in many number theory tasks.

n = 17
if n % 2 == 0:
    print("Even")
else:
    print("Odd")
Coding Q14. Count how many times a specific element appears in a list.

Definition: Frequency counting is core logic in analytics, hashing, and data grouping tasks.

nums = [1,2,3,2,4,2,5]
target = 2
count = nums.count(target)
print(count)
Coding Q15. Write a program to merge two lists into one.

Definition: List merging is used everywhere in data processing, ETL pipelines, and batch operations.

a = [1, 2, 3]
b = [4, 5, 6]
merged = a + b
print(merged)
Coding Q16. Write a Python program to check whether a substring exists in a string.

Definition: Substring search is foundational for NLP, search engines, and text matching.

s = "Hello Python"
print("Python" in s)
Coding Q17. Convert a list of numbers into their squares.

Definition: Mapping each value to a new value is used in transformations and feature engineering.

nums = [1,2,3,4]
squares = [n*n for n in nums]
print(squares)
Coding Q18. Write a program to print Fibonacci numbers up to n terms.

Definition: Fibonacci logic is a classic interview question to test loop-based generation patterns.

n = 6
a, b = 0, 1
for _ in range(n):
    print(a)
    a, b = b, a + b
Coding Q19. Convert a list of strings to uppercase.

Definition: String transformation tasks are common in preprocessing, NLP, and cleaning pipelines.

words = ["apple", "banana", "cat"]
upper = [w.upper() for w in words]
print(upper)
Coding Q20. Find the index of the first occurrence of an element in a list.

Definition: Index searching is a key skill used in searching algorithms and list operations.

nums = [3,5,7,5,8]
target = 5
print(nums.index(target))
Coding Q21. Write a Python program to count the frequency of each element in a list without using Counter().

Definition: Frequency counting is used in hashing, grouping, NLP token counting, and competitive programming.

nums = [1,2,2,3,3,3]
freq = {}

for n in nums:
    if n not in freq:
        freq[n] = 1
    else:
        freq[n] += 1

print(freq)
Coding Q22. Write a program to remove duplicates from a list while maintaining order.

Definition: Ordered de-duplication is important in databases, streaming logs, and real-time processing.

nums = [1,2,2,3,1,4,3]
result = []

for x in nums:
    if x not in result:
        result.append(x)

print(result)
Coding Q23. Write a function to return the second smallest value in a list.

Definition: Second-min/second-max logic appears in leaderboard ranking and array problem solving.

nums = [10,4,2,8,15]
unique = sorted(set(nums))
print(unique[1])
Coding Q24. Write a program to check if two strings are anagrams of each other.

Definition: Anagram checks are used in NLP preprocessing, string hashing, and interview filtering rounds.

s1 = "listen"
s2 = "silent"

print(sorted(s1) == sorted(s2))
Coding Q25. Write a program to find all pairs in a list whose sum is equal to a given number.

Definition: Pair-sum problems are core for DSA, 2-pointer algorithms, and coding interviews.

nums = [1,2,3,4,5]
target = 6

for i in range(len(nums)):
    for j in range(i+1, len(nums)):
        if nums[i] + nums[j] == target:
            print(nums[i], nums[j])
Coding Q26. Write a program to find the longest word in a sentence.

Definition: Longest-word extraction is used in NLP, token analysis, and summarization tools.

s = "Python coding interview preparation"
words = s.split()
longest = max(words, key=len)

print(longest)
Coding Q27. Write a program to rotate a list by k positions.

Definition: Rotation logic appears in circular queues and time-series window shifting.

nums = [1,2,3,4,5]
k = 2
k = k % len(nums)

rotated = nums[-k:] + nums[:-k]
print(rotated)
Coding Q28. Write a program to flatten a 2D list into a 1D list.

Definition: Flattening is heavily used in ML preprocessing, matrix-to-vector transformation, and ETL pipelines.

matrix = [[1,2],[3,4],[5,6]]
flat = [n for row in matrix for n in row]

print(flat)
Coding Q29. Write a program to remove special characters from a string.

Definition: Cleaning text is a crucial part of NLP preprocessing and data sanitization.

s = "He!!o P@th#n"
clean = "".join(ch for ch in s if ch.isalnum() or ch == " ")
print(clean)
Coding Q30. Write a Python function to check if a list is sorted or not.

Definition: Sorted check is used in binary search, data validation, and signal processing.

nums = [1,2,3,4,5]
print(nums == sorted(nums))
Coding Q31. Find the first non-repeating character in a string (without using OrderedDict).

Definition: Identifying the first unique element is a common FAANG string-processing problem requiring optimal hashing.

s = "aabbcddeff"
freq = {}

for ch in s:
    freq[ch] = freq.get(ch, 0) + 1

for ch in s:
    if freq[ch] == 1:
        print("First non-repeating:", ch)
        break
Coding Q32. Implement a function to return all duplicate elements in a list (using O(n) time).

Definition: Optimized duplicate finding is a very common hashing interview challenge.

nums = [1,2,3,2,4,5,3,6,3]
seen = set()
dups = set()

for n in nums:
    if n in seen:
        dups.add(n)
    else:
        seen.add(n)

print(dups)
Coding Q33. Write a function to check if two lists are rotations of each other.

Definition: Rotational equivalence is used in pattern recognition and cyclic structure checks.

a = [1,2,3,4,5]
b = [3,4,5,1,2]

check = " ".join(map(str,a))
target = " ".join(map(str,b))

print(target in (check + " " + check))
Coding Q34. Reverse the words in a sentence without using split().

Definition: Manual tokenization checks your ability to process strings at a low level.

s = "Python is super powerful"
word = ""
words = []

for ch in s + " ":
    if ch != " ":
        word += ch
    else:
        words.append(word)
        word = ""

print(" ".join(words[::-1]))
Coding Q35. Find the longest increasing continuous subsequence in a list.

Definition: This sliding window pattern appears repeatedly in Amazon & Google interviews.

nums = [1,2,2,3,4,1,2,3,4,5]
best = curr = 1

for i in range(1, len(nums)):
    if nums[i] > nums[i-1]:
        curr += 1
    else:
        curr = 1
    best = max(best, curr)

print(best)
Coding Q36. Implement binary search without using recursion.

Definition: Binary search is the most essential DSA concept; FAANG expects clean implementation.

nums = [1,3,5,7,9,11]
target = 7

low, high = 0, len(nums)-1
found = False

while low <= high:
    mid = (low + high) // 2
    if nums[mid] == target:
        found = True
        break
    elif nums[mid] < target:
        low = mid + 1
    else:
        high = mid - 1

print("Found?", found)
Coding Q37. Find the majority element in a list (element appearing more than n/2 times).

Definition: This uses the Boyer–Moore Voting Algorithm β€” a very popular interview problem.

nums = [3,3,4,2,3,3,1]
count = 0
candidate = None

for n in nums:
    if count == 0:
        candidate = n
    count += 1 if n == candidate else -1

print("Majority Element:", candidate)
Coding Q38. Given a matrix, print its transpose without using NumPy.

Definition: Matrix manipulation is important in ML, AI pipelines, and basic DSA.

mat = [[1,2,3],[4,5,6],[7,8,9]]
transpose = []

for col in range(len(mat[0])):
    row_vals = []
    for row in range(len(mat)):
        row_vals.append(mat[row][col])
    transpose.append(row_vals)

print(transpose)
Coding Q39. Implement a function to find missing numbers in a range without using sets.

Definition: Missing-number logic appears in array scanning & validation problems.

nums = [1,2,4,6,7]
start, end = 1, 7
miss = []

for i in range(start, end+1):
    if i not in nums:
        miss.append(i)

print(miss)
Coding Q40. Reverse a linked list (using list simulation, since Python has no built-in linked list).

Definition: FAANG tests linked-list logic heavily. Here we simulate using tuples.

linked = [1,2,3,4,5]
rev = linked[::-1]
print(rev)
Coding Q41. Write a function to compute the power (x^n) using fast exponentiation (log n).

Definition: Fast exponentiation reduces time complexity from O(n) β†’ O(log n).

def fast_pow(x, n):
    result = 1
    while n > 0:
        if n % 2 == 1:
            result *= x
        x *= x
        n //= 2
    return result

print(fast_pow(2, 10))
Coding Q42. Implement a simple LRU Cache using a dictionary + list (not OrderedDict).

Definition: LRU Cache is a top-tier system design + coding interview problem.

capacity = 3
cache = []
store = {}

def access(key, value=None):
    if key in store:
        cache.remove(key)
    else:
        if len(cache) == capacity:
            old = cache.pop(0)  
            del store[old]
        store[key] = value
    cache.append(key)

access("A", 1)
access("B", 2)
access("C", 3)
access("A")
access("D", 4)

print(store)
Coding Q43. Given a list, generate all its subsets (power set).

Definition: Subset generation is a core recursion/backtracking pattern used in FAANG interviews.

nums = [1,2,3]
res = [[]]

for n in nums:
    res += [subset + [n] for subset in res]

print(res)
Coding Q44. Write a program to solve the classic Two-Sum problem using hashing (O(n)).

Definition: Two-sum is the most asked DSA question in FAANG coding interviews.

nums = [2,7,11,15]
target = 9
seen = {}

for i, v in enumerate(nums):
    diff = target - v
    if diff in seen:
        print([seen[diff], i])
        break
    seen[v] = i
Coding Q45. Generate all permutations of a list without using itertools.

Definition: Backtracking for permutation generation is a classic advanced coding test.

res = []

def permute(nums, path=[]):
    if not nums:
        res.append(path)
        return
    for i in range(len(nums)):
        permute(nums[:i] + nums[i+1:], path + [nums[i]])

permute([1,2,3])
print(res)
Coding Q46. Implement a function to compute Fibonacci using memoization (DP).

Definition: Memoization eliminates repeated calculations, drastically improving recursion performance.

memo = {}

def fib(n):
    if n <= 1:
        return n
    if n in memo:
        return memo[n]
    memo[n] = fib(n-1) + fib(n-2)
    return memo[n]

print(fib(10))
Coding Q47. Find the longest palindrome substring in a string (Expand Around Center method).

Definition: Palindrome substring detection is a very common string DP/interview pattern.

def longest_pal(s):
    res = ""
    for i in range(len(s)):
        # Odd length
        l, r = i, i
        while l >= 0 and r < len(s) and s[l]==s[r]:
            if (r-l+1) > len(res):
                res = s[l:r+1]
            l -= 1; r += 1
        
        # Even length
        l, r = i, i+1
        while l >= 0 and r < len(s) and s[l]==s[r]:
            if (r-l+1) > len(res):
                res = s[l:r+1]
            l -= 1; r += 1

    return res

print(longest_pal("babad"))
Coding Q48. Implement "Merge Intervals" (Google-level problem).

Definition: Merging overlapping intervals appears in scheduling, memory blocks, and OS allocation algorithms.

intervals = [[1,3],[2,6],[8,10],[15,18]]
intervals.sort()
merged = []

for i in intervals:
    if not merged or merged[-1][1] < i[0]:
        merged.append(i)
    else:
        merged[-1][1] = max(merged[-1][1], i[1])

print(merged)
Coding Q49. Solve "Trapping Rain Water" problem (Hard).

Definition: Uses two-pointer technique to calculate stored water β€” asked frequently in Amazon/Google.

height = [4,2,0,3,2,5]
left, right = 0, len(height)-1
lmax = rmax = 0
water = 0

while left < right:
    if height[left] < height[right]:
        if height[left] >= lmax:
            lmax = height[left]
        else:
            water += lmax - height[left]
        left += 1
    else:
        if height[right] >= rmax:
            rmax = height[right]
        else:
            water += rmax - height[right]
        right -= 1

print(water)
Coding Q50. Solve the "Minimum Window Substring" problem (Sliding Window Advanced).

Definition: One of the toughest sliding-window questions β€” asked in Meta & Bloomberg.

s = "ADOBECODEBANC"
t = "ABC"

from collections import Counter
need = Counter(t)
missing = len(t)
left = start = end = 0

for right, ch in enumerate(s, 1):
    if need[ch] > 0:
        missing -= 1
    need[ch] -= 1

    if missing == 0:
        while left < right and need[s[left]] < 0:
            need[s[left]] += 1
            left += 1
        if end == 0 or right-left < end-start:
            start, end = left, right

print(s[start:end])
Coding Q51. Implement a function to find the longest common prefix among a list of strings.

Definition: LCP is used heavily in trie structures, autocomplete systems, and string grouping.

strs = ["flower","flow","flight"]

prefix = strs[0]
for s in strs[1:]:
    while not s.startswith(prefix):
        prefix = prefix[:-1]

print(prefix)
Coding Q52. Find all permutations of a string using recursion (without lists).

Definition: Pure recursive permutation generation β€” testing depth-first logic.

def perm(s, path=""):
    if not s:
        print(path)
        return
    for i in range(len(s)):
        perm(s[:i] + s[i+1:], path + s[i])

perm("abc")
Coding Q53. Implement matrix multiplication manually (no NumPy).

Definition: A fundamental ML operation and common DSA exam question.

A = [[1,2],[3,4]]
B = [[5,6],[7,8]]

res = [[0,0],[0,0]]

for i in range(2):
    for j in range(2):
        for k in range(2):
            res[i][j] += A[i][k] * B[k][j]

print(res)
Coding Q54. Validate balanced parentheses using a stack (classic).

Definition: Stack-based bracket matching is essential in compiler design + code parsing.

s = "{[()]}[]"
stack = []
pairs = {')':'(',']':'[','}':'{'}

valid = True
for ch in s:
    if ch in "([{":
        stack.append(ch)
    else:
        if not stack or stack[-1] != pairs[ch]:
            valid = False
            break
        stack.pop()

valid = valid and not stack
print(valid)
Coding Q55. Solve the Coin Change problem using DP (minimum coins).

Definition: Dynamic programming classic β€” used in optimization interviews.

coins = [1,2,5]
amount = 11
dp = [float("inf")] * (amount+1)
dp[0] = 0

for c in coins:
    for a in range(c, amount+1):
        dp[a] = min(dp[a], dp[a-c] + 1)

print(dp[amount])
Coding Q56. Find all combinations that sum to a target (Backtracking).

Definition: Backtracking search appears heavily in Amazon/Meta coding rounds.

nums = [2,3,6,7]
target = 7
res = []

def dfs(i, total, path):
    if total == target:
        res.append(path)
        return
    if total > target or i == len(nums):
        return
    dfs(i, total + nums[i], path + [nums[i]])
    dfs(i+1, total, path)

dfs(0,0,[])
print(res)
Coding Q57. Implement Kadane’s Algorithm to find maximum subarray sum.

Definition: Kadane’s is the best-known dynamic programming array technique.

nums = [-2,1,-3,4,-1,2,1,-5,4]
best = curr = nums[0]

for n in nums[1:]:
    curr = max(n, curr+n)
    best = max(best, curr)

print(best)
Coding Q58. Rotate a matrix 90 degrees clockwise (in-place logic style).

Definition: Rotation logic is used in image processing and 2D array manipulation.

mat = [
    [1,2,3],
    [4,5,6],
    [7,8,9]
]

rot = []
for c in range(len(mat)):
    row = []
    for r in range(len(mat)-1, -1, -1):
        row.append(mat[r][c])
    rot.append(row)

print(rot)
Coding Q59. Find the longest substring without repeating characters (O(n) sliding window).

Definition: This is a top 3 most repeated FAANG question.

s = "abcabcbb"
seen = {}
start = longest = 0

for i,ch in enumerate(s):
    if ch in seen and seen[ch] >= start:
        start = seen[ch] + 1
    seen[ch] = i
    longest = max(longest, i - start + 1)

print(longest)
Coding Q60. Solve N-Queens Problem (Backtracking β€” FAANG Hard).

Definition: N-Queens is a core backtracking algorithm asked in senior-level Python roles.

N = 4
res = []

def solve(row, cols, diag1, diag2, path):
    if row == N:
        res.append(path)
        return
    for col in range(N):
        if col not in cols and (row+col) not in diag1 and (row-col) not in diag2:
            solve(row+1, cols|{col}, diag1|{row+col}, diag2|{row-col}, path+[col])

solve(0, set(), set(), set(), [])
print(res)