[Python-ideas] How assignment should work with generators?

Alon Snir AlonSnir at hotmail.com
Tue Nov 28 13:46:18 EST 2017

I would like to mention that the issue of assignment to a target list, is also relevant to the case of elementwise assignment to a mutable sequence (e.g. lists and arrays). Here as well, the rhs of the assignment statement states the number of elements to be assigned. Consequently, the following example will get into infinite loop:

>>> from itertools import count
>>> A = []
>>> A[:] = count()

Writing "A[:2] = count()" will cause the same result.
Here as well, it is currently safer to use islice if the rhs is a generator or an iterator. e.g.:

>>> it = count()
>>> A[:] = islice(it,2)

In my opinion, it is be better to devise a solution that could be applied in both cases. Maybe a new kind of assignment operator that will be dedicated to this kind of assignment. i.e. elementwise assignment with restriction on the number of elements to be assigned, based on the length of the lhs object (or the number of targets in the target list).

More information about the Python-ideas mailing list