9 Python One-Liners I Now Use in Every Project Without Thinking Twice Quiz

Sharpen your backend Python skills with these essential, production-proven one-liners for safe, efficient, and clean code practices.

  1. Safe Dictionary Access

    Which one-liner allows you to retrieve a value from a dictionary safely, returning a default if the key does not exist?

    1. value = my_dict.find('key')
    2. value = my_dict.get('key', 'default')
    3. value = my_dict['key']
    4. value = my_dict.pop('key')

    Explanation: Using my_dict.get('key', 'default') safely accesses dictionary values and returns a default if the key is missing. my_dict['key'] throws a KeyError if the key is absent. my_dict.pop('key') removes the item and fails if not present. my_dict.find('key') is not a valid method for dictionaries.

  2. Compact List Filtering

    What is the most concise way to filter even numbers from a list in Python using a one-liner?

    1. [x % 2 == 0 for x in numbers]
    2. [x for x in numbers if x % 2 == 0]
    3. map(lambda x: x % 2 == 0, numbers)
    4. filter(lambda x: x % 2, numbers)

    Explanation: [x for x in numbers if x % 2 == 0] is the most readable and concise one-liner to filter even numbers. filter(lambda x: x % 2, numbers) filters out even numbers incorrectly (keeps odds). map returns a list of booleans, not filtered values. [x % 2 == 0 for x in numbers] creates a list of True/False, not actual numbers.

  3. Default Value Assignment

    Which one-liner assigns a default value to a variable only if it is currently None?

    1. if value is None: value = 'default'
    2. value = value and 'default'
    3. value = value or 'default'
    4. value = 'default' if value is None else value

    Explanation: value = value or 'default' assigns 'default' if value is None or any falsy value. The ternary version works but is less concise. The if statement is not a true one-liner. value = value and 'default' would return 'default' only if value is truthy, which is often incorrect for this use.

  4. Reversing Strings Easily

    How can you reverse a string in Python in a single line?

    1. reversed_string = ''.reverse(original)
    2. reversed_string = reverse(original)
    3. reversed_string = original[::-1]
    4. reversed_string = original.reverse()

    Explanation: original[::-1] quickly reverses a string using slicing. original.reverse() and ''.reverse(original) are not valid string methods. reverse(original) does not exist in standard Python.

  5. Flattening Nested Lists

    Which Python one-liner can flatten a 2D list of lists into a single list?

    1. [item for sublist in lists for item in sublist]
    2. flatten(lists)
    3. lists.flatten()
    4. sum(lists)

    Explanation: [item for sublist in lists for item in sublist] flattens 2D lists via nested comprehension. lists.flatten() and flatten(lists) are not standard methods. sum(lists) tries to sum lists, raising an error.