-1

itertools.chain is said to convert chain('ABC', 'DEF') --> A B C D E F. Yet, I see that

>>> Set(itertools.chain([(1,2,3),(4,5,6)]))
Set([(4, 5, 6), (1, 2, 3)])

I see that no hierarchy is affected. Similarly, list(itertools.chain([[1,2,3],[4,5,6]])) is said to have effect on lists. But I see no flattening in my case

>>> list(itertools.chain([[1,2,3],[4,5,6]]))
[[1, 2, 3], [4, 5, 6]]

What the hell is going on?

Community
  • 1
  • 1

2 Answers2

2

What the hell is going on?

You misread the answer you referenced

In that answer was this line:

merged = list(itertools.chain(*list2d))

Note the use of the asterisk (or 'splat') operator.

In your question, there is no such operator:

>>> list(itertools.chain([[1,2,3],[4,5,6]]))  
[[1, 2, 3], [4, 5, 6]]

To make sense of the answer you reference, try this:

>>> list(itertools.chain(*[[1,2,3],[4,5,6]]))
[1, 2, 3, 4, 5, 6]

Which is equivalent to removing the outer-most brackets:

>>> list(itertools.chain([1,2,3],[4,5,6]))
[1, 2, 3, 4, 5, 6]
Community
  • 1
  • 1
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
1

The fist argument is a list of iterables (tuples) not one iterable. You can use chain.from_iterable() to flatten your list:

>>> from itertools import chain
>>> list(chain.from_iterable([(1,2,3),(4,5,6)]))
[1, 2, 3, 4, 5, 6]
Mazdak
  • 105,000
  • 18
  • 159
  • 188