s[i:j:t] = t stipulation

Neil Cerutti horpner at yahoo.com
Tue Nov 20 19:08:44 CET 2007

s[i:j:t] = t (1) t must have the same length as the slice it is


>>> def foo():
...   while True:
...     yield 'a'
>>> foo()
>>> x = range(10)
>>> x[::2] = foo()

This is infinite loop due to Python building a sequence out of
the iterator to check its length.

I think it might be more useful for 

x[::2] = foo()

to result in an x of

['a', 1, 'a', 3, 'a', 5, 'a', 7, 'a', 9]

In other words, take (j-i)//k elements from t for abs(k) != 1.

A problem, though, arises when t is too short--the sequence
could be corrupted before an exception is thrown if you omit the
length check.

So you'd also have to define

x[::2] = 'aaa'

as resulting in

['a', 1, 'a', 2, 'a', 3, 5, 7, 9]

But perhaps that's just adding more useless complexity to the
already complex slicing rules (kudos for 'slice.indices', though
curses that the method isn't cross-referenced in more places).

Neil Cerutti

More information about the Python-list mailing list