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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With