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.
What is printed?
easy
print(type(3 / 1).__name__)- int
- float
- number
- 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.
What is printed?
easy
x = [10, 20, 30] print(x[-2])- 10
- 20
- 30
- IndexError
Answer: B. 20
Explanation: Negative indexes count from the end: -1 is the last item, -2 the one before it.
Which statement creates an empty set?
easy
- s = {}
- s = set()
- s = []
- s = ()
Answer: B. s = set()
Explanation: {} creates an empty dictionary. An empty set has no literal syntax, so you call set().
What is printed?
easy
print("a,b,,c".split(","))- ['a', 'b', 'c']
- ['a', 'b', '', 'c']
- ['a,b,,c']
- ['a', 'b', ',', 'c']
Answer: B. ['a', 'b', '', 'c']
Explanation: split with an explicit separator keeps empty strings between consecutive separators.
What is printed?
medium
d = {"x": 1, "y": 2} for k, v in d.items(): d[k] = v * 10 print(sum(d.values()))- 3
- 30
- 12
- 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.
What is printed?
medium
print(list(zip([1, 2, 3], "ab")))- [(1, 'a'), (2, 'b')]
- [(1, 'a'), (2, 'b'), (3, None)]
- [(1, 2, 3), ('a', 'b')]
- ValueError
Answer: A. [(1, 'a'), (2, 'b')]
Explanation: zip stops at the shortest input. itertools.zip_longest pads the shorter one instead.
What is printed?
medium
s = "hello" print(s.replace("l", "L", 1), s)- heLlo hello
- heLLo heLLo
- heLlo heLlo
- 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.
What is printed?
medium
nums = [3, 1, 2] result = nums.sort() print(result, nums)- [1, 2, 3] [1, 2, 3]
- None [1, 2, 3]
- None [3, 1, 2]
- [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.
What is printed?
hard
def f(): try: return "try" finally: print("finally", end=" ") print(f())- try
- finally try
- try finally
- finally
Answer: B. finally try
Explanation: The finally block runs before the function actually returns, so "finally" is printed first, then the returned value.
What is printed?
hard
a = 256 b = 256 c = [1] d = [1] print(a == b, c == d, c is d)- True True False
- True True True
- True False False
- 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.
What is printed?
hard
squares = (x * x for x in range(4)) print(sum(squares), sum(squares))- 14 14
- 14 0
- 0 14
- 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.
Which statements about Python dictionaries are true? (Select all that apply)
hard
- Since Python 3.7 they keep insertion order
- Keys must be hashable
- Average lookup time is O(log n)
- 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
Which of these is immutable?
Python · easy
- list
- dict
- set
- 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.
What is printed?
Python · hard
print(all([]), any([]), bool([[]]))- True False True
- False False False
- True True True
- 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.
What is printed?
Python · easy
nums = [1, 2, 3, 4, 5] print(nums[1:4])- [1, 2, 3, 4]
- [2, 3, 4]
- [2, 3, 4, 5]
- [1, 2, 3]
Answer: B. [2, 3, 4]
Explanation: Slices include the start index and exclude the end: indexes 1, 2 and 3.
What is printed?
Python · easy
print(7 // 2, 7 % 2, 7 / 2)- 3 1 3.5
- 3.5 1 3
- 3 1 3
- 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).
What is printed?
Python · hard
def gen(): x = yield 1 yield x * 10 g = gen() print(next(g), g.send(5))- 1 50
- 1 10
- 1 None
- 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.
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)- 0 1 1
- 2 2 2
- 2 1 2
- 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.
What is printed?
Python · medium
def add(item, box=[]): box.append(item) return box add(1) print(add(2))- [2]
- [1, 2]
- []
- 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.
What is printed?
Python · medium
x = 10 def f(): x = 20 def g(): nonlocal x x += 1 g() return x print(f(), x)- 21 10
- 21 21
- 11 10
- 20 10
Answer: A. 21 10
Explanation: nonlocal makes g change f’s x (20 → 21). The global x stays 10.
What is printed?
Python · medium
print(sorted(["banana", "Apple", "cherry"]))- ['Apple', 'banana', 'cherry']
- ['apple', 'banana', 'cherry']
- ['banana', 'cherry', 'Apple']
- ['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.