ProgrammingHardTCS NQT · Wipro pattern

What is printed?

What is printed?
print([n for n in range(8) if n and n & (n - 1) == 0])
  1. A. [1, 2, 4]
  2. B. [0, 1, 2, 4]
  3. C. [1, 2, 4, 8]
  4. D. [2, 4]

Correct answer: A. [1, 2, 4]

n & (n - 1) is zero only when n has a single set bit. The range stops at 7, so 8 is not included, and 0 is excluded by the n test.

More Python Programming questions

Exams that ask this topic