How does python sum of a 2d array return a list

Viewed 116

I came across a piece of python code where the sum function of a 2d array evaluates to a list.

For example:

a = [['a','b','c'],['d','e','f'],['g','h','i']]]

sum(a,[]) returns ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

Why does this happen? Maybe I'm missing something basic, but would like to understand the mechanics of this.

2 Answers

sum(iterable, /, start=0):

Sums start and the items of an iterable from left to right and returns the total

So for your code, the operation produced by sum is

[] + ['a','b','c'] + ['d','e','f'] + ['g','h','i']

which is a list concatenation, and produces:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

Note that if you don't supply the start value of [], sum uses the default start value of 0 and performs:

0 + ['a','b','c'] + ['d','e','f'] + ['g','h','i']

which results in a TypeError:

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

Hopefully you Can Understand It Simply Like Here

a = [['a','b','c'],['d','e','f'],['g','h','i']]

It is Doing It as Follows :

result = []
for list in a:
    result += list

And Now returning The Result List :

print(result)

I Also Informs you That That Above method Is Fast From sum(a, []) Method

Sum Function Does not Works Like That But You Can Understand Easily By This That How It Works

Related