+ 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?
14 Respostas
+ 3
my_list = [1,2,3,4,5]
print(sum(i for i in my_list if not my_list.index(i) % 2))
+ 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 :)
+ 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)
+ 2
Brian R glad to see people like you trying to help as well!
+ 1
Oopsâtotally forgot it could be done like that. Thanks for correcting me!
+ 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!
+ 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
+ 1
ah thatâs what I was looking for!
its sum(a, start)
+ 1
Quan Nguyen no, this only specifes the start, nothing related to even indexes (except in the case of patterns)
+ 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?
+ 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
+ 1
oh got it
+ 1
Thanks everyone! Thanks David Ashton! I think I liked your solution the best!
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))