3

I've found one strange thing in Python 3.6. Following code returns

TypeError: unsupported operand type(s) for +: 'int' and 'list'

arr = [1, 2, 3, 4, 5]
print(sum([[i] for i in arr]))

Why does it happen? How can I summarize a list of lists?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
DeadUnicorn
  • 175
  • 1
  • 12

4 Answers4

7

Here's the help from the REPL:

>>> help(sum)

sum(iterable, start=0, /)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

So, the sum built-in returns the sum of the start value, i.e. 0, and an iterable of numbers. Python doesn't prevent you from misusing a function beforehand, it trusts that you are at least trying to do the right thing. Of course, if you happen to pass a list-of-lists, the first list element will be summed with 0, raising:

TypeError: unsupported operand type(s) for +: 'int' and 'list'

Indeed, if you pass a start argument, an empty list, in this case, it works:

>>> sum([[e] for e in x], [])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

However, this will be inefficient. You should prefer [x for sublist in list_of_lists for x in sublist] or any other linear time algorithm.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
1

First of all, your [[i] for i in arr] returns [[1], [2], [3], [4], [5]].

Why not just simply print the sum of the array:

print(sum(arr))

Or, if you don't want to change your [[i] for i in arr]:

print(sum([[i] for i in arr], []))

I prefer using sum(arr) though, shorter code and readable.

kiyah
  • 1,502
  • 2
  • 18
  • 27
0

You should use it this way.

print (sum(i for i in arr))

If you use parenthesis around 'i' like [i], this means 'i' is a element in a tuple, and you can't possibly add a integer, with a list.

TypeError: unsupported operand type(s) for +: 'int' and 'list' --> It means it cannot add integer with a list. Because when you use a for loop, it gives you a single element each time, the loop is executed i.e., an integer, but you are expecting a list to be returned to sum() function. Therefore it doesn't work that way.

Sandvip
  • 11
  • 4
-1

Just do...

arr = [1, 2, 3, 4, 5]
print sum(arr)

You want to sum multiple elements. You already have a list to input to function. Why would you want a list comprehension, using the list you already have ?

If you want to flatten a list of list into a single list, in order to sum it all, you could watch this thread, and use sum as I did above.

IMCoins
  • 3,149
  • 1
  • 10
  • 25