Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Was this possible in Python before [any previous version]

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

like image 886
codingsenpi Avatar asked Apr 28 '26 03:04

codingsenpi


1 Answers

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.

like image 108
U12-Forward Avatar answered Apr 29 '26 18:04

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!