2

I remember vaguely that this thing was working a long time ago Does anybody know that if this code really worked before? and if this was deprecated since any newer python version?

code

# My python version is 3.8

lst = ['a', 'b', 'c', 'd']
lst[0:3] = 100
print(lst)

current output

TypeError: can only assign an iterable

expected output

[100, 'd']

Thanks

codingsenpi
  • 71
  • 1
  • 6

2 Answers2

10

This doesn't work in any version because slicing assignment requires a sequence-like object to assign as.

The reason it doesn't work is because you need to convert it to a single itemed sequence, like the below:

lst = ['a', 'b', 'c', 'd']
lst[:3] = [100]
print(lst)

Or with a tuple:

lst = ['a', 'b', 'c', 'd']
lst[:3] = 100,
print(lst)

Since lst[:3] gives an sequence object, the object you assign it to also needs to be a sequence object.

This wouldn't possible in any version in python... For indexing not using a single itemed sequence would be the only way. Like this:

lst = ['a', 'b', 'c', 'd']
lst[3] = 100
print(lst)

But for slicing sequences would be required for all python versions.

As mentioned in the documentation for python 3, documentation of python 2:

The length of the slice may be different from the length of the assigned sequence, thus changing the length of the target sequence, if the target sequence allows it.

As I see in the documentation of Python 1.4:

If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (e.g. a list). The assigned object should be a sequence object of the same type.

This documentation was released in 1996.

So for 25 years, this couldn't be possible, python docs was in 1996, but actually python 1 started in 1994.

All version documentation references are the same.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
6

For Python's own built in type this has not been possible before, at least in the past 20 years and more.

Assignment Statements

If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (e.g. a list). The assigned object should be a sequence object of the same type. […]

-- Python 1.4, documentation released on 25 October 1996.

The same statement is present in all published documentation up to the current version.


Note that as per the data model, semantically Python does not have such a restriction.

Data Model: Emulating sequence and mapping types

__setslice__(self, i, j, sequence) Called to implement assignment to self[i:j]. The sequence argument can have any type. The return value should be None. Same notes for i and j as for __getslice__.

-- Python 1.4, documentation released on 25 October 1996.

Custom types, most prominently numpy.array, are free to interpret slice assignment of scalars as they please.

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119