Language: Python
A. Lists are immutable, and tuples are mutable.
B. Lists store heterogeneous elements, while tuples store homogeneous elements.
C. Lists are ordered collections and mutable; tuples are ordered collections and immutable.
D. Lists use parentheses (), and tuples use square brackets [].
Correct Answer: C. Lists are ordered collections of items that are mutable, meaning their elements can be changed after creation. Tuples are also ordered collections, but they are immutable, meaning their elements cannot be changed once the tuple is created.
Code for Correct Answer (Illustrative):
# Lists are mutable
my_list = [1, 2, 3]
my_list[0] = 10
print(my_list) # Output: [10, 2, 3]
# Tuples are immutable
my_tuple = (1, 2, 3)
try:
my_tuple[0] = 10
except TypeError as e:
print(f"Error: {e}") # Output: Error: 'tuple' object does not support item assignment
A. Using if/else statements for error checking.
B. By ignoring potential errors and letting the program crash.
C. Using try, except, else, and finally blocks.
D. With the error keyword followed by the error type.
Correct Answer: C. Python provides a robust mechanism for handling exceptions using try, except, else, and finally blocks. This allows for graceful error management and prevents program termination.
Code for Correct Answer:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Result: {result}") # This block executes if no exception occurred
finally:
print("This block always executes, regardless of exception.")
__init__ method in Python classes?A. It's a method used to destroy an object when it's no longer needed.
B. It's a special method called automatically when an object is created, used for initializing object attributes.
C. It's a method for performing arithmetic operations within a class.
D. It defines how an object is represented as a string.
Correct Answer: B. The __init__ method is a constructor in Python. It's automatically invoked when a new instance (object) of a class is created, and it's primarily used to initialize the attributes of that object.
Code for Correct Answer:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
print(f"{self.name} the {self.breed} has been created!")
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.name) # Output: Buddy
A. Curly braces {}
B. Parentheses ()
C. Indentation
D. Keywords like BEGIN and END
Correct Answer: C. Unlike many other programming languages that use curly braces or keywords, Python uses indentation to define code blocks, such as those within functions, loops, and conditional statements. This contributes to Python's readability.
Code for Correct Answer (Illustrative):
def greet(name):
if name:
print(f"Hello, {name}!") # This line is indented, part of the 'if' block
else:
print("Hello there!") # This line is indented, part of the 'else' block
A. Functions that delete other functions.
B. Functions that modify the behavior of other functions or methods without permanently altering their code.
C. Built-in data structures for storing key-value pairs.
D. Keywords used for defining loops.
Correct Answer: B. Decorators are a powerful and elegant way to extend or modify the behavior of functions or methods. They allow you to wrap another function, thereby extending the wrapped function's behavior, without explicitly modifying it.
Code for Correct Answer:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# Output:
# Something is happening before the function is called.
# Hello!
# Something is happening after the function is called.
A. The GIL is a mechanism that allows multiple threads to execute Python bytecode simultaneously.
B. The GIL is a mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecodes1 at once.
C. The GIL is a security feature that prevents unauthorized access to Python code.
D. The GIL is a tool for distributing Python programs across multiple machines.
Correct Answer: B. The Global Interpreter Lock (GIL) is a mutex (or a lock) that allows only one native thread to execute Python bytecodes at a time, even on multi-core processors. While it simplifies memory management, it can limit true parallel execution in CPU-bound multi-threaded applications.
== and is in Python?A. == compares the identity of two objects, while is compares their values.
B. == and is are interchangeable and have the same meaning.
C. == compares the values of two objects, while is compares their identity (memory location).
D. == is used for numbers, and is is used for strings.
Correct Answer: C. The == operator checks for value equality (do the objects have the same content?). The is operator checks for identity equality (do the objects refer to the same memory location?).
Code for Correct Answer:
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print(list1 == list2) # Output: True (values are the same)
print(list1 is list2) # Output: False (different objects in memory)
print(list1 is list3) # Output: True (both refer to the same object)
A. A function that returns a list of items.
B. A function that generates random numbers.
C. A function that returns an iterator for a sequence of values, pausing execution and saving its state between calls.
D. A special type of loop statement.
Correct Answer: C. Generators are functions that return an iterator. They produce values one at a time, on demand, using the yield keyword. This makes them memory-efficient, especially when dealing with large sequences, as they don't generate all values at once.
Code for Correct Answer:
def fibonacci_generator(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# Using the generator
for num in fibonacci_generator(5):
print(num)
# Output:
# 0
# 1
# 1
# 2
# 3
A. Manually by the programmer using malloc() and free().
B. Automatically using a private heap space and a garbage collector with reference counting.
C. By offloading memory management to the operating system.
D. Python does not manage memory; it's handled by the underlying hardware.
Correct Answer: B. Python uses a private heap space for memory management, where all Python objects and data structures reside. It employs an automatic garbage collector, primarily using a reference counting mechanism. When an object's reference count drops to zero, its memory is deallocated. Python also has a cyclic garbage collector to detect and break reference cycles.
A. PEP 8 is a Python package manager used for installing libraries.
B. PEP 8 is the official style guide for writing readable and consistent Python code.
C. PEP 8 is a framework for web development in Python.
D. PEP 8 is a standard for database connectivity in Python.
Correct Answer: B. PEP 8 (Python Enhancement Proposal 8) is the official style guide for Python code. It provides conventions for writing clear, readable, and maintainable code, promoting2 consistency across the vast Python ecosystem. Adhering to PEP 8 makes your code easier for others (and your future self!) to understand and work with.
By understanding these fundamental and frequently asked Python concepts, you'll be well-equipped to tackle various programming challenges and confidently answer questions in technical discussions or interviews. Keep coding, keep learning, and remember that consistent practice is key to becoming a master Python programmer!