+ 1

String summing

So I understand that if you code, print(sum([1,2,3,4,5]) The result is 15. Is there a way to just sum the even indexes?

31st Dec 2019, 1:29 AM
Quan Nguyen
Quan Nguyen - avatar
14 odpowiedzi
+ 3
my_list = [1,2,3,4,5] print(sum(i for i in my_list if not my_list.index(i) % 2))
31st Dec 2019, 5:02 AM
David Ashton
David Ashton - avatar
+ 7
Brian R definitely not the only way, this is just the most classic way Quan Nguyen you can use list slicing: L = [1, 2, 3, 4, 5] # or ant list you want s = sum(L[::2]) NOTE: There is always a way to do anything, you just have to think :)
31st Dec 2019, 1:44 AM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 3
I think the only way you can sum the even indexes is by iterating through the list manually. Here's an example: my_list = [1, 2, 3, 4, 5] sum = 0 for i in range(len(my_list)) if i % 2 == 0: sum += my_list[i] print(sum)
31st Dec 2019, 1:37 AM
Brian R
Brian R - avatar
+ 2
Brian R glad to see people like you trying to help as well!
31st Dec 2019, 1:47 AM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 1
Oops—totally forgot it could be done like that. Thanks for correcting me!
31st Dec 2019, 1:45 AM
Brian R
Brian R - avatar
+ 1
thanks fellow coders! gives me some insight. I was just wondering if there was some sort of extra coding in the pre built in functions!
31st Dec 2019, 1:48 AM
Quan Nguyen
Quan Nguyen - avatar
+ 1
Quan Nguyen you can always check for the source code to see what other parameters can be used as well. Anyway, here it is, without the source code: https://www.google.com/amp/s/www.geeksforgeeks.org/sum-function-JUMP_LINK__&&__python__&&__JUMP_LINK/amp/ Answer: no there isn't
31st Dec 2019, 1:50 AM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 1
ah that’s what I was looking for! its sum(a, start)
31st Dec 2019, 1:51 AM
Quan Nguyen
Quan Nguyen - avatar
+ 1
Quan Nguyen no, this only specifes the start, nothing related to even indexes (except in the case of patterns)
31st Dec 2019, 1:52 AM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 1
so i think how that works is it will sum string a, and if i put 2 in start it will sum all the second variables?
31st Dec 2019, 1:52 AM
Quan Nguyen
Quan Nguyen - avatar
+ 1
Quan Nguyen it will start from the third, rememeber, indexes start from 0 not 1. And no, it will sum the variables from index 2 to the end of list
31st Dec 2019, 1:53 AM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 1
oh got it
31st Dec 2019, 1:54 AM
Quan Nguyen
Quan Nguyen - avatar
+ 1
Thanks everyone! Thanks David Ashton! I think I liked your solution the best!
1st Jan 2020, 12:01 AM
Quan Nguyen
Quan Nguyen - avatar
0
L=(1,2,3,4,5,6,7,8,9) m=round(len(L)/2) n=L[:m] print(sum(L)-2*sum(n))
31st Dec 2019, 8:40 PM
Ferhad Mislim
Ferhad Mislim - avatar