What is the primary purpose of decorators in Python?
To change the behavior of a function without modifying its source code.
To improve the performance of a function.
To create recursive functions.
To define a function within another function.
What will the following code snippet print?
d = {} d.setdefault('a', []).append(1) print(d['a'])
[1]
KeyError: 'a'
[]
1
Which regular expression will match any string that starts with 'a' and ends with 'z'?
'^a.*z$'
'a.+z'
'a.*z'
'^a.+z$'
Which code snippet correctly creates a dictionary where keys are numbers from 1 to 5 and values are their squares using a dictionary comprehension?
{num**2: num for num in range(1, 6)}
(num: num**2 for num in range(1, 6))
[num: num**2 for num in range(1, 6)]
{num: num**2 for num in range(1, 6)}
Which concept in OOP emphasizes providing a simplified view of an object, hiding its complexity?
Abstraction
Encapsulation
Inheritance
Polymorphism
Which data structure would be most appropriate for representing a graph in Python?
A set of tuples, where each tuple represents an edge between two nodes.
A dictionary where keys are nodes, and values are lists of their neighbors.
A list of lists, where each inner list represents a node and its connections.
All of the above options can be used to represent a graph.
What differentiates a deque from a regular Python list?
deque
Deques can only store integers, while lists can store any data type.
Deques are thread-safe, while lists are not.
Deques are optimized for appending and popping elements from both ends, while lists are optimized for operations at the end.
Deques are immutable, while lists are mutable.
How can you access the constant 'pi' from the 'math' module after importing it?
math.pi
math->pi
pi
math(pi)
Which data structure from the collections module is best suited for efficiently keeping track of element frequencies?
collections
Counter
defaultdict
OrderedDict
What is the purpose of the finally block in Python exception handling?
finally
It executes only if an exception occurs in the try block.
try
It defines a custom exception to be raised.
It always executes after a try block, regardless of whether an exception occurred.
It specifies the type of exception to catch.