Home > other >  Python Sum with 3 nested list and empty list Explanation
Python Sum with 3 nested list and empty list Explanation

Time:10-08

l = [ [[1,2,3], [2,3,4]] ]
sum(l,[])

Output ist

[[1, 2, 3], [2, 3, 4]]

I don't know why it works like this.

I tired the two below

[].__add__(l) # First Try


[]   l # Secodn Try

In both cases, the output was as follows.

[[[1, 2, 3], [2, 3, 4]]]

I don't know what the difference is from the sum operation.

My python version is 3.8.12

CodePudding user response:

sum takes a list of values and adds all of them together. E.g. for a list of numbers:

l = [1, 2, 3]
sum(l)

does:

0   1   2   3

As you see, the outer list does not appear in the operations nor result.

Now, with your example:

l = [ [[1,2,3], [2,3,4]] ]
sum(l, [])

that's concatenating all the values in l:

[]   [[1,2,3], [2,3,4]]

Which is not the same as:

[]   [ [[1,2,3], [2,3,4]] ]

CodePudding user response:

If I understand correctly you want to add 1 to every item in the list, if so this code should work.

x = [[[1,2,3], [2,3,4]]]

for i in range(len(x[0])):
    for j in range(len(x[0][i])):
        x[0][i][j]  = 1

print(x)
  • Related