Needless copying in iterations?

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Sun Sep 16 02:24:09 EDT 2007


On Sun, 16 Sep 2007 00:40:13 +0000, Steven D'Aprano wrote:

> On Sun, 16 Sep 2007 00:05:58 +0000, Marc 'BlackJack' Rintsch wrote:
> 
> In *general* the compiler can't tell, but in specific cases it could. A 
> (hypothetical) optimizing compiler would tell the difference between:
> 
> 
> for item in alist[1:5]:
>     print item # no possible side-effects

To expand on what Ben said:  After conversion to `str` the result is then
given to `sys.stdout.write()` and of course `sys.stdout` could be another
object that changes `alist`.

> for item in alist[1:5]:
>     alist.append(item) # side-effects DON'T matter

Side effect do matter here, even in not so pathological cases.  There are
cases where you get a different result whether you copy or not even with
plain vanilla `list`\s:

In [153]: alist = [1, 2, 3]

In [154]: for item in alist[1:5]:
   .....:     alist.append(item)
   .....:

In [155]: alist
Out[155]: [1, 2, 3, 2, 3]

In [156]: alist = [1, 2, 3]

In [157]: for item in islice(alist, 1, 5):
   .....:     alist.append(item)
   .....:

In [158]: alist
Out[158]: [1, 2, 3, 2, 3, 2, 3]

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list