On Sun, 2021-06-20 at 13:48 -0400, David Mertz wrote: > On Sun, Jun 20, 2021 at 1:07 PM Christopher Barker < > python...@gmail.com> > wrote: > > > Flatten is used in numpy: > > Where it is a method, and goes all the way to one dimension. > > > > I think it's worth keeping in mind the differences though. In NumPy, > arr.flatten() doesn't even TOUCH the array itself. It is solely a > manipulation of the `.shape` attribute. In essence, we could define > it > like this:
Passer by comment. But that is not true: `flatten` explicitly copies the data and does not create a view (in case the argument was about names). NumPy has: * `flatten()` (alwasy copy) * `ravel()` (copies if needed, and additionally ensures contiguity) * `reshape(-1)` (copies if needed) They are all subtly different, unfortunately. - Sebastian > > arr.flatten = lambda a: a.reshape(reduce(mul, a.shape, 1)) > > Actual NumPy arrays don't allow attaching a monkey-patch method, but > if > they did that would be it. I guess this example relies on knowing > that > `.reshape` also doesn't touch the data though (in particular, zero > memory > copies). > > A builtin flatten can’t be the same, but it would be nice if it > weren’t too > > different. e.g. list(flatten(a_2d_array)) would do the same thing > > as > > list(a_2d_array.flatten()). > > For a builtin, perhaps it could take an optional integer “depth” > > parameter > > which would provide flexibility and be one way to control its > > behavior with > > strings. > > > > I think that would be nice as a signature. I don't really care about > builtin vs itertools, but something like `flatten(seq, depth=2)` > would be > handy. The question is really whether the default depth is 1 or > sys.maxsize. Both have plausible cases. Some special depth like 2 > or 3 > could be useful at times, but definitely should not be default. > > _______________________________________________ > Python-ideas mailing list -- python-ideas@python.org > To unsubscribe send an email to python-ideas-le...@python.org > https://mail.python.org/mailman3/lists/python-ideas.python.org/ > Message archived at > https://mail.python.org/archives/list/python-ideas@python.org/message/UAJVPXSXR3JNBTEOPEPTWHAZIQUM637N/ > Code of Conduct: http://python.org/psf/codeofconduct/ _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/DSQ6USYIRET5IP66NG6UGFVXBC2MKRWU/ Code of Conduct: http://python.org/psf/codeofconduct/