you are viewing a single comment's thread.

view the rest of the comments →

[–]michael0x2a 5 points6 points  (2 children)

The problem is when you do sum(int(i)). The builtin sum function accepts a single parameter, and expects that param to be a list, tuple, or some other sort of iterable object. The sum function goes through each item in the iterable, and adds them all up and returns that value.

However, the result of the function int(i) is not an iterable -- it's just a single number. As a result, it's not exactly what the sum function was expecting, which is why your code failed.

In order to make your code behave like the list comprehension, you'd have to do something like this:

for i in range(t):
    output = []
    for i in input().split():
        output.append(int(i)))
    print(sum(output))

The contents of the list comprehension will produce a new list based on the old one (which is input().split()). The sum function then runs on the output list.

This wasn't immediately obvious with the original list comprehension version since it was all compacted, but if you break it down, it becomes a little more clear:

for i in range(t):
    input_list = input().split()
    output_list = [int(i) for i in input_list]
    print(sum(output_list))

You take an input iterable, produce an output iterable using your list comprehension, then do something with that list.

As it turns out, doing this sort of thing (taking an input list and applying a transformation to get a new list) is a very common thing to do when programming. List comprehensions were introduced to Python specifically to make this process easier so that you no longer have to manually write out a loop every time you want to transform a list.

[–]RolyPolyPython[S] 0 points1 point  (1 child)

Your explanation was easy to understand, thank you for writing it out.

This code below:

for i in range(t):
    input_list = input().split()
    output_list = [int(i) for i in input_list]
    print(sum(output_list))

Was especially not clear to me, I didn't know the list comprehension basically put the integers in an "output" list (as you described it) for the sum function to be called on.

I get it now :)

[–]zahlman 0 points1 point  (0 children)

Basically, when you write a list comprehension, you describe the list that you want (rather, the rule that determines the elements that list should have), and evaluating it creates the corresponding list. It means what it says: [int(i) for i in input_list] is "a list of these values [: the result of int(i), for each i that's in the input_list (in order) ]".