Interview Questions in Python - Beginner Level

  • What are f-strings in Python, and how do they improve string formatting?

F-strings (formatted string literals) were introduced in Python 3.6 to improve string formatting by making it more readable and efficient. Instead of using .format() or % formatting, f-strings allow direct variable insertion using {}.

Benefits:

  • More readable and concise
  • Faster execution compared to .format()
  • Supports expressions inside {}
				
					name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
				
			
  • How does Python’s walrus operator work, and where is it useful?

The walrus operator (:=) introduced in Python 3.8 allows assignment inside an expression. It is useful in loops and conditions where a value needs to be assigned and checked simultaneously.

Use cases:

  • Reduces redundancy in loops
  • Improves performance by avoiding redundant calculations
				
					while (n := len(input("Enter string: "))) > 5: 
        print(f"Length is {n}, try a shorter string.")
				
			
  • Explain the difference between is and == in Python.

== compares values (whether two objects have the same content) while is compares identities (whether two variables point to the same memory location).

				
					a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)  # True (values are the same)
print(a is b)  # False (different memory locations)
				
			
  • Why is Python’s enumerate() function preferred over a traditional loop with range(len())?

enumerate() provides an index while iterating, making code cleaner and more readable compared to range(len()).

Advantages:

  • Improves readability
  • Avoids potential off-by-one errors
  • More Pythonic and efficient
				
					names = ["Alice", "Bob", "Charlie"]
for index, name in enumerate(names, start=1):
    print(f"{index}: {name}")
				
			
  • What is the difference between mutable and immutable types in Python?

Mutable objects can be changed after creation (e.g., lists, dictionaries, sets).
Immutable objects cannot be changed after creation (e.g., tuples, strings, integers).

				
					# Mutable (List)
my_list = [1, 2, 3]
my_list[0] = 10     # Allowed
print(my_list)      # Output: [10, 2, 3]

# Immutable (Tuple)
my_tuple = (1, 2, 3)
# my_tuple[0] = 10  # TypeError: 'tuple' object does not support item assignment
				
			
  • What are Python’s built-in data structures, and when should you use each?
    • List ([]) – Ordered, mutable, allows duplicates. Use when the order is important.
    • Tuple (()) – Ordered, immutable, allows duplicates. Use when data shouldn’t change.
    • Set ({}) – Unordered, mutable, no duplicates. Use for unique items.
    • Dictionary ({key: value}) – Key-value pairs, fast lookups. Use for mapping data.
  • What is the difference between *args and **kwargs in Python functions?
    • *args allows passing a variable number of positional arguments.
    • **kwargs allows passing a variable number of keyword arguments.
				
					def demo_function(*args, **kwargs):
    print("Positional:", args)
    print("Keyword:", kwargs)

demo_function(1, 2, 3, name="edSlash", age=25)
# Output:
# Positional: (1, 2, 3)
# Keyword: {'name': 'edSlash', 'age': 25}

				
			
  • What is the purpose of zip() in Python?

    The zip() function combines multiple iterables element-wise into tuples.

				
					names = ["edSlash", "Coding", "Hub", "Gwalior"]
ages = [25, 20, 22, 27]

combined = list(zip(names, ages))
print(combined)  # [('edSlash', 25), ('Coding', 20), ('Hub', 22), ('Gwalior', 27)]
				
			
  • What are lambda functions, and how are they used?

    Lambda functions are anonymous, single-expression functions used for short tasks.

				
					square = lambda x: x ** 2
print(square(5))  # Output: 25
				
			
				
					students = [("Alice", 25), ("Bob", 20), ("Charlie", 22)]
students.sort(key=lambda x: x[1])  # Sort by age
print(students)  # [('Bob', 20), ('Charlie', 22), ('Alice', 25)]
				
			
				
					nums = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, nums))
print(squared)  # [1, 4, 9, 16]
				
			
  • What is list comprehension, and how does it improve code readability?

    List comprehensions provide a concise way to create lists.

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

squares = [x**2 for x in range(5)]
print(squares)  # [0, 1, 4, 9, 16]

# Both codes will give the same output but the 2nd one is smaller.
				
			
  • How does exception handling work in Python, and why is it important?

    Exception handling prevents programs from crashing due to unexpected errors.

				
					try:
    x = 1 / 0  # ZeroDivisionError
except ZeroDivisionError:
    print("You cannot divide by zero!")
finally:
    print("This will always execute.")
  
# Output ---  
# You cannot divide by zero!
# This will always execute.

				
			
  • How does the in keyword work in Python?

    The in keyword is used to check if a data value is member of a sequence (lists, tuples, sets, dict or strings) or not.

				
					print("edSlash" in ["Coding", "edSlash", "Hub"])

# --- Output ---
# True
				
			
  • What is __name__ == "__main__" in Python?

    It ensures that a script(Python code) runs only when executed directly, not when imported as a module.

				
					def greet():
    print("Hello, world!")

if __name__ == "__main__":
    greet()  # Runs only if the script is executed directly

				
			
  • What are Python’s map(), filter(), and reduce() functions?
    • map(func, iterable): Applies a function to all elements.
    • filter(func, iterable): Filters elements based on a condition.
    • reduce(func, iterable): Reduces an iterable to a single value (needs functools).
				
					from functools import reduce

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

squared = list(map(lambda x: x**2, nums))
filtered = list(filter(lambda x: x % 2 == 0, nums))
summed = reduce(lambda x, y: x + y, nums)

print(squared)   # [1, 4, 9, 16, 25]
print(filtered)  # [2, 4]
print(summed)    # 15

				
			
  • What is the difference between deepcopy() and copy() in Python?
    • copy() creates a shallow copy, meaning it copies only the reference to nested objects.
    • deepcopy() creates an independent deep copy of all nested objects.
				
					import copy

original = [[1, 2, 3], [4, 5, 6]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)

original[0][0] = 99
print(shallow[0][0])  # 99 (Shallow copy affected)
print(deep[0][0])     # 1 (Deep copy remains unchanged)
				
			
  • How do you merge two dictionaries in Python?
				
					dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}

merged = {**dict1, **dict2}  # Using dictionary unpacking
print(merged)                # {'a': 1, 'b': 3, 'c': 4}

dict1.update(dict2)          # Using update()
print(dict1)                 # {'a': 1, 'b': 3, 'c': 4}
				
			
  • What is the difference between isinstance() and type() in Python?
    • isinstance(obj, Class): Checks if an object is an instance of a class (including subclasses).
    • type(obj): Checks the exact type (ignores inheritance).
				
					print(isinstance(5, int))     # True
print(isinstance(True, int))  # True (since bool is a subclass of int)

print(type(5) == int)         # True
print(type(True) == int)      # False
				
			
  • What are f-strings in Python, and why are they useful?

    f-strings (formatted string literals) allow embedding expressions inside string literals using {}. They are more readable and efficient than older formatting methods like format() and %.

				
					name = "edSlash"
age = 28
print(f"My name is {name} and I am {age} years old.")

# Output: My name is edSlash and I am 28 years old.
				
			
  • How do you remove duplicate elements from a list in Python?
				
					# Using set() (order is lost):

nums = [1, 2, 2, 3, 4, 4, 5]
unique_nums = list(set(nums))
print(unique_nums)  # Output: [1, 2, 3, 4, 5]


# Using dict.fromkeys() (preserves order):
unique_nums = list(dict.fromkeys(nums))
print(unique_nums)  # Output: [1, 2, 3, 4, 5]


# Using list comprehension:
unique_nums = []
[unique_nums.append(num) for num in nums if num not in unique_nums]
print(unique_nums)  # Output: [1, 2, 3, 4, 5]