2

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?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
onesick
  • 21
  • 1
  • what does nums have? – ggaurav Jan 03 '21 at 04:43
  • `nums[i]` is an `int` which is not iterable (as the error message says), whereas `nums[i],` is a `tuple`, which is iterable. What you probably wanted to do here was `res.append(nums[i])` - using `res += ...` is equivalent to `res.extend(...)` which means the right-hand side must be iterable. – kaya3 Jan 03 '21 at 04:44
  • It is not about the comma, but the variable `nums`. In the first instance variable `nums` must be an integer. So, it throws an error. In the second instance it must be `list`, therefore there won't be any error. – SAI SANTOSH CHIRAG Jan 03 '21 at 04:44

1 Answers1

4

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.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114