x=[1,2,5]
y=[2,3,9]
how can I get the result 22?
my code has type error.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I think you want the built-in
sumfunction.This is the same thing as:
or if you love itertools:
with the latter 2 being more efficient.
sumtakes an iterable and sums all of it’s elements. when dealing with lists+concatenates, so:gives you the list:
which is iterable and therefore a perfect candidate for
sum.If you have a whole bunch of lists you could make this even more interesting:
This last form is nice because it scales trivially up to an arbitrary number of lists — just keep appending them to the
listslist until you’re ready to sum, pop that 1-liner in there and then you’re done.Of course, I suppose we could do the same thing with itertools as well:
As you can see, you have quite a few options to play with (and learn from! :).