Sharpen your Python skills for backend development in 2025 with these essential language tricks and lesser-known features. Boost code readability, efficiency, and reliability with practical, modern Python know-how.
Which of the following code snippets correctly uses the walrus operator (:=) to read input until 'quit' is entered?
Explanation: The correct use of the walrus operator assigns input() to 'line' and compares it to 'quit' in the while condition. Option B improperly assigns 'quit' inside the input, which is invalid. Option C never stores the input. Option D tries to assign to 'quit', which is not allowed. Only A is syntactically valid and achieves the intended functionality.
What will be the output of 'a, *b, c = [1, 2, 3, 4, 5]' and what does the asterisk (*) do?
Explanation: The asterisk (*) in unpacking collects all items between the two fixed ends into a list assigned to 'b'. The other options incorrectly assign the asterisk to the wrong variable or misrepresent the output structure. Only collecting the middle elements into a list is correct for this pattern.
How can you merge two dictionaries 'd1' and 'd2' into a new dictionary in Python 3.9+?
Explanation: Starting with Python 3.9, the '|' operator allows merging two dictionaries, producing a new one. The '+' operator is invalid for dictionaries. 'merge()' and '.merge()' are not built-in dictionary methods in Python. The vertical bar operator is the recommended modern approach.
Which built-in Python function allows looping over a list while having access to both index and value at once?
Explanation: The enumerate() function returns pairs of (index, value) when iterating over an iterable. zip() combines two or more iterables. map() and filter() process iterables but do not provide index information directly. Only enumerate() provides both index and item cleanly.
Why is using 'pathlib.Path' preferred over using raw string paths in modern Python for file and directory operations?
Explanation: pathlib.Path makes path handling more readable and robust, supports both Windows and Unix-like systems, and provides object-oriented methods. It does not guarantee faster execution, force absolute paths, or require asynchronous operations. Its main benefit is maintaining consistent, readable, and cross-platform file paths.