Python questions and answers

Data types, comprehensions and mutability. Practise python questions from the technical & programming section of placement tests, with a worked explanation after every answer. Practice is free and needs no sign-up.

Sample python questions with worked answers

Question 1

Which of the following Python built-in types is immutable?

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

Answer: B. tuple

Explanation: A tuple cannot be changed after creation (no item assignment, append or remove). list, dict and set can all be modified in place.

Question 2

What will be the output of the following Python code?

print([x * x for x in range(6) if x % 2])
  1. [0, 4, 16]
  2. [1, 9, 25]
  3. [1, 9, 25, 49]
  4. [0, 1, 4, 9, 16, 25]

Answer: B. [1, 9, 25]

Explanation: range(6) gives 0 to 5. x % 2 is truthy only for odd x (1, 3, 5), and their squares are 1, 9 and 25.

Question 3

What will be the output of the following Python code?

fs = [lambda: i for i in range(3)]
print([f() for f in fs])
  1. [0, 1, 2]
  2. [0, 0, 0]
  3. [2, 2, 2]
  4. NameError

Answer: C. [2, 2, 2]

Explanation: Each lambda looks up i when it is called, not when it is created (late binding). By then the comprehension has finished with i = 2, so all three return 2.

All 30 python questions with answers

Python: common questions

What are python questions?

Data types, comprehensions and mutability. They appear in the technical & programming section of many placement tests.

Where can I practise python questions with answers for free?

Right here on LogicWiz Exams. Every python question has a worked explanation after you answer. Practice is free and needs no sign-up.

How should I practise python?

Start with easy questions, then move to medium and hard. Read the explanation after each answer, and come back to the ones you missed.

Start practising

On this page you can start a fresh set of python questions, choose easy, medium or hard, and time yourself if you want to. Or practise the whole subject: Technical & Programming practice.

More technical & programming topics

Other subjects

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge · Test from a job description · LogicWiz Open: free team quiz · Free interview prep