Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How this works: print(sum(int(x) for x in raw_input().split())) in Python

Tags:

python

I am very new in Python, and I am really surprised at the following line of code.

print (sum(int(x) for x in raw_input().split()))

I cannot understand what is happening inside with my Java brain, especially the way x passed to int() from for loop.

like image 465
Heejin Avatar asked Feb 04 '12 21:02

Heejin


3 Answers

First, raw_input().split() reads a line which is then split into its whitespace-separated components. So a line like 1 3 2 5 7 3 becomes the list ['1', '3', '2', '5', '7', '3'].

This list is used in a generator expression int(x) for x in list_above. This expression evaluates to a generator which transforms the elements of the list into their int() representations.

This generator is evaluated during the call of sum(), which adds up all the numbers.

like image 32
glglgl Avatar answered Oct 06 '22 01:10

glglgl


raw_input().split() returns an array for each line of input. (int(x) for x in a) is a generator expression which applies int to each line of input, converting it to an integer. The result of the generator expression is an array of integers; one for each line of input.

Finally sum takes the sum of all the elements in the array, and of course print will output the whole lot. So the result is code which produces the sum of all lines of input where each line is a number.

like image 73
Michael Mior Avatar answered Oct 06 '22 00:10

Michael Mior


Lets break it down.

print (sum(int(x) for x in raw_input().split()))

Is also expressed as

sequence = raw_input().split()
conv = []
for i in sequence:
    conv.append(int(i))
print sum(conv)

Now we can combine this into one line using

[int(x) for x in raw_input().split()]

But this is not lazy, So to make it lazy we simply replace the [ with (

(int(x) for x in raw_input().split())

Now because this is an iterable object we can now pass this to sum()

And that is what is happening.

like image 35
Jakob Bowyer Avatar answered Oct 06 '22 01:10

Jakob Bowyer