Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Python 3, and slice operand with comma

I came to a notation in python where I iterate len(nums) like this: where

res = []
res += nums[i]

and I get the TypeError: 'int' object is not iterable error message. However, If I do,

res += nums[i],

the expression passes. I tried to look Python doc, but couldn't find the reference. Can you please help me locate it or explain why I need a comma for slice iteration additions?

question from:https://stackoverflow.com/questions/65546693/python-3-and-slice-operand-with-comma

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

1 Answer

0 votes
by (71.8m points)

Your nums list is probably a 1d list, let's say the list is:

nums = [1, 2, 3]

Then when you index the nums list:

nums[i]

It will give you a value of 1 or 2 or 3.

But single values can't be added to a list:

>>> [] + 1
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    [] + 1
TypeError: can only concatenate list (not "int") to list
>>> 

But your second code works because adding a comma makes a single value into a tuple, like below:

>>> 1,
(1,)
>>> 

So of course:

>>> res = []
>>> res += (1,)
>>> res
[1]
>>> 

Works.

It doesn't only work with , comma, if you do:

>>> res = []
>>> res += [1]
>>> res
[1]
>>> 

It will work too.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...