Hack4Hack

Python practice questions with answers

Practise Python questions at your own pace: output questions, lists, dicts, strings, closures, generators, exceptions and OOP. Pick an answer to see whether you are right and why. Nothing is timed or ranked here; for that, play the Daily Quiz at 4 PM IST.

  1. What is printed?

    easy

    print(type(3 / 1).__name__)
    1. int
    2. float
    3. number
    4. double

    Answer: B. float

    Explanation: In Python 3 the / operator always returns a float, even when the result is a whole number. Use // for integer (floor) division.

  2. What is printed?

    easy

    x = [10, 20, 30]
    print(x[-2])
    1. 10
    2. 20
    3. 30
    4. IndexError

    Answer: B. 20

    Explanation: Negative indexes count from the end: -1 is the last item, -2 the one before it.

  3. Which statement creates an empty set?

    easy

    1. s = {}
    2. s = set()
    3. s = []
    4. s = ()

    Answer: B. s = set()

    Explanation: {} creates an empty dictionary. An empty set has no literal syntax, so you call set().

  4. What is printed?

    easy

    print("a,b,,c".split(","))
    1. ['a', 'b', 'c']
    2. ['a', 'b', '', 'c']
    3. ['a,b,,c']
    4. ['a', 'b', ',', 'c']

    Answer: B. ['a', 'b', '', 'c']

    Explanation: split with an explicit separator keeps empty strings between consecutive separators.

  5. What is printed?

    medium

    d = {"x": 1, "y": 2}
    for k, v in d.items():
        d[k] = v * 10
    print(sum(d.values()))
    1. 3
    2. 30
    3. 12
    4. RuntimeError

    Answer: B. 30

    Explanation: Changing the values of existing keys while looping is allowed (adding or removing keys is not). The values become 10 and 20.

  6. What is printed?

    medium

    print(list(zip([1, 2, 3], "ab")))
    1. [(1, 'a'), (2, 'b')]
    2. [(1, 'a'), (2, 'b'), (3, None)]
    3. [(1, 2, 3), ('a', 'b')]
    4. ValueError

    Answer: A. [(1, 'a'), (2, 'b')]

    Explanation: zip stops at the shortest input. itertools.zip_longest pads the shorter one instead.

  7. What is printed?

    medium

    s = "hello"
    print(s.replace("l", "L", 1), s)
    1. heLlo hello
    2. heLLo heLLo
    3. heLlo heLlo
    4. heLLo hello

    Answer: A. heLlo hello

    Explanation: The third argument limits the number of replacements to 1. Strings are immutable, so s itself is unchanged.

  8. What is printed?

    medium

    nums = [3, 1, 2]
    result = nums.sort()
    print(result, nums)
    1. [1, 2, 3] [1, 2, 3]
    2. None [1, 2, 3]
    3. None [3, 1, 2]
    4. [1, 2, 3] [3, 1, 2]

    Answer: B. None [1, 2, 3]

    Explanation: list.sort() sorts in place and returns None. sorted(nums) returns a new sorted list instead.

  9. What is printed?

    hard

    def f():
        try:
            return "try"
        finally:
            print("finally", end=" ")
    
    print(f())
    1. try
    2. finally try
    3. try finally
    4. finally

    Answer: B. finally try

    Explanation: The finally block runs before the function actually returns, so "finally" is printed first, then the returned value.

  10. What is printed?

    hard

    a = 256
    b = 256
    c = [1]
    d = [1]
    print(a == b, c == d, c is d)
    1. True True False
    2. True True True
    3. True False False
    4. False True False

    Answer: A. True True False

    Explanation: The two lists are equal in value (==) but are two different objects, so "is" is False. Never use "is" to compare values.

  11. What is printed?

    hard

    squares = (x * x for x in range(4))
    print(sum(squares), sum(squares))
    1. 14 14
    2. 14 0
    3. 0 14
    4. 6 6

    Answer: B. 14 0

    Explanation: A generator can only be consumed once. The first sum uses it up (0 + 1 + 4 + 9 = 14), so the second sum sees nothing.

  12. Which statements about Python dictionaries are true? (Select all that apply)

    hard

    1. Since Python 3.7 they keep insertion order
    2. Keys must be hashable
    3. Average lookup time is O(log n)
    4. A list can be used as a key

    Answer: A. Since Python 3.7 they keep insertion order; B. Keys must be hashable

    Explanation: Dicts are hash tables with O(1) average lookups. Keys must be hashable, so mutable lists cannot be keys (tuples of hashable items can).

From past Daily Quizzes

  1. Which of these is immutable?

    Python · easy

    1. list
    2. dict
    3. set
    4. tuple

    Answer: D. tuple

    Explanation: A tuple cannot be changed after it is created, which is also why tuples (of hashable items) can be dictionary keys.

  2. What is printed?

    Python · hard

    print(all([]), any([]), bool([[]]))
    1. True False True
    2. False False False
    3. True True True
    4. False False True

    Answer: A. True False True

    Explanation: all() of nothing is True (no element is false), any() of nothing is False. [[]] is a non-empty list, so it is truthy even though its item is empty.

  3. What is printed?

    Python · easy

    nums = [1, 2, 3, 4, 5]
    print(nums[1:4])
    1. [1, 2, 3, 4]
    2. [2, 3, 4]
    3. [2, 3, 4, 5]
    4. [1, 2, 3]

    Answer: B. [2, 3, 4]

    Explanation: Slices include the start index and exclude the end: indexes 1, 2 and 3.

  4. What is printed?

    Python · easy

    print(7 // 2, 7 % 2, 7 / 2)
    1. 3 1 3.5
    2. 3.5 1 3
    3. 3 1 3
    4. 4 1 3.5

    Answer: A. 3 1 3.5

    Explanation: // is floor division (3), % is the remainder (1), and / always returns a float in Python 3 (3.5).

  5. What is printed?

    Python · hard

    def gen():
        x = yield 1
        yield x * 10
    
    g = gen()
    print(next(g), g.send(5))
    1. 1 50
    2. 1 10
    3. 1 None
    4. TypeError

    Answer: A. 1 50

    Explanation: next(g) runs to the first yield and gives 1. send(5) resumes the generator, making the paused yield expression evaluate to 5, so the next yield gives 50.

  6. What is printed?

    Python · hard

    class Counter:
        count = 0
        def __init__(self):
            self.count += 1
    
    a, b = Counter(), Counter()
    print(Counter.count, a.count, b.count)
    1. 0 1 1
    2. 2 2 2
    3. 2 1 2
    4. 0 0 0

    Answer: A. 0 1 1

    Explanation: self.count += 1 reads the class attribute (0) but writes a new instance attribute. The class attribute is never changed. Write Counter.count += 1 to share it.

  7. What is printed?

    Python · medium

    def add(item, box=[]):
        box.append(item)
        return box
    
    add(1)
    print(add(2))
    1. [2]
    2. [1, 2]
    3. []
    4. An error

    Answer: B. [1, 2]

    Explanation: Default values are evaluated once, when the function is defined. Both calls share the same list. Use box=None and create the list inside.

  8. What is printed?

    Python · medium

    x = 10
    def f():
        x = 20
        def g():
            nonlocal x
            x += 1
        g()
        return x
    print(f(), x)
    1. 21 10
    2. 21 21
    3. 11 10
    4. 20 10

    Answer: A. 21 10

    Explanation: nonlocal makes g change f’s x (20 → 21). The global x stays 10.

  9. What is printed?

    Python · medium

    print(sorted(["banana", "Apple", "cherry"]))
    1. ['Apple', 'banana', 'cherry']
    2. ['apple', 'banana', 'cherry']
    3. ['banana', 'cherry', 'Apple']
    4. ['cherry', 'banana', 'Apple']

    Answer: A. ['Apple', 'banana', 'cherry']

    Explanation: Strings sort by code point, and capital letters come before lowercase ones, so "Apple" is first here. Use key=str.lower to sort case-insensitively.

Play the Daily Quiz at 4 PM IST