Please consider the two snippets of code (notice the distinction between string and integer):
a = []
a[:] = '1'
and
a = []
a[:] = 1
In the first case a is ['1']. In the second, I get the error TypeError: can only assign an iterable. Why would using '1' over 1 be fundamentally different here?
Assigning to a slice requires an iterable on the right-hand side.
'1'is iterable, while1is not. Consider the following:The result is:
As you can see, the list gets each character of the string as a separate item. This is a consequence of the fact that iterating over a string yields its characters.
If you want to replace a range of
a‘s elements with a single scalar, simply wrap the scalar in an iterable of some sort:This also applies to strings (provided the string is to be treated as a single item and not as a sequence of characters):