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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With