This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: functools.reduce doesn't work properly with itertools.chain
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 3.6
process
Status: closed Resolution:
Dependencies: Superseder:
Assigned To: rhettinger Nosy List: Vasantha Ganesh Kanniappan, josh.r, rhettinger
Priority: normal Keywords:

Created on 2018-10-22 11:49 by Vasantha Ganesh Kanniappan, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (4)
msg328248 - (view) Author: Vasantha Ganesh Kanniappan (Vasantha Ganesh Kanniappan) Date: 2018-10-22 11:49
I'm facing this issue in python 3.6.5

How to reproduce:

my_list = [[1, 2], [3, 4]]
a = reduce(itertools.chain, my_list)

The output of `a' is [1, 2, 3, 4] as expected, but now 
my_list is [[1, 2, 3, 4], [3, 4]]
msg328264 - (view) Author: Josh Rosenberg (josh.r) * (Python triager) Date: 2018-10-22 16:21
Your example code doesn't behave the way you claim. my_list isn't changed, and `a` is a chain generator, not a list (without a further list wrapping).

In any event, there is no reason to involve reduce here. chain already handles varargs what you're trying to do without involving reduce at all:

a = list(itertools.chain(*my_list))

or if you prefer to avoid unnecessary unpacking:

a = list(itertools.chain.from_iterable(*my_list))

Either way, a will be [1, 2, 3, 4], and my_list will be unchanged, with no wasteful use of reduce.
msg328287 - (view) Author: Vasantha Ganesh Kanniappan (Vasantha Ganesh Kanniappan) Date: 2018-10-23 07:02
You are right. It works now. I'm sorry for wasting your time.
msg328350 - (view) Author: Josh Rosenberg (josh.r) * (Python triager) Date: 2018-10-24 01:42
Blech. Copy'n'paste error in last post:

a = list(itertools.chain.from_iterable(*my_list))

should be:

a = list(itertools.chain.from_iterable(my_list))

(Note removal of *, which is the whole point of from_iterable)
History
Date User Action Args
2022-04-11 14:59:07adminsetgithub: 79224
2018-10-24 01:42:55josh.rsetmessages: + msg328350
2018-10-23 07:02:22Vasantha Ganesh Kanniappansetstatus: open -> closed

messages: + msg328287
stage: resolved
2018-10-22 17:33:08rhettingersetassignee: rhettinger

nosy: + rhettinger
2018-10-22 16:21:35josh.rsetnosy: + josh.r
messages: + msg328264
2018-10-22 11:49:58Vasantha Ganesh Kanniappancreate