Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

python - Why is a[:]=1 fundamentally different to a[:]='1'?

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?

question from:https://stackoverflow.com/questions/9045169/why-is-a-1-fundamentally-different-to-a-1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assigning to a slice requires an iterable on the right-hand side.

'1' is iterable, while 1 is not. Consider the following:

In [7]: a=[]

In [8]: a[:]='abc'

The result is:

In [9]: a
Out[9]: ['a', 'b', 'c']

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:

In [11]: a[:]=(1,) # single-element tuple

In [12]: a
Out[12]: [1]

This also applies to strings (provided the string is to be treated as a single item and not as a sequence of characters):

In [17]: a[:]=('abc',)

In [18]: a
Out[18]: ['abc']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...