ProgrammingHardAccenture pattern

What is printed?

What is printed?
import itertools
print(list(itertools.chain([1, 2], [3, 4])))
print(list(itertools.chain.from_iterable([[1, 2], [3, 4]])))
  1. A. [[1, 2], [3, 4]] [1, 2, 3, 4]
  2. B. [1, 2, 3, 4] [1, 2, 3, 4]
  3. C. [1, 2, 3, 4] [[1, 2], [3, 4]]
  4. D. [1, 2, [3, 4]] [1, 2, 3, 4]

Correct answer: B. [1, 2, 3, 4] [1, 2, 3, 4]

chain concatenates the given iterables end to end, giving [1,2,3,4]. chain.from_iterable does the same but takes a single iterable OF iterables as input, here also flattening to [1,2,3,4]. Both produce the identical flat result here.

More Python Programming questions

Exams that ask this topic