Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use range(len(list)) to find the product of all even-indexed integers in a list?

Tags:

python

list

I'm very new to coding, and I'm doing an assignment where I have to find the product of all even-indexed integers in a huge list:

number_list = [12, 41, 10, 34, 37, 2, 3, 8, 42, 46, 46, 27, 13, 49, 41, 2, 28, 21, 37, 27, 31, 19, 46, 7, 50, 1, 46, 45, 19, 10, 14, 8, 44, 14, 10, 4, 23, 29, 46, 18, 32, 40, 32, 7, 33, 45, 26, 24, 43, 45]

The question recommends using range(len(list)), which gives me range (1,50), but I don't see how that's relevant. I managed to get the answer without using that method:

number_list = [12, 41, 10, 34, 37, 2, 3, 8, 42, 46, 46, 27, 13, 49, 41, 2, 28, 21, 37, 27, 31, 19, 46, 7, 50, 1, 46, 45, 19, 10, 14, 8, 44, 14, 10, 4, 23, 29, 46, 18, 32, 40, 32, 7, 33, 45, 26, 24, 43, 45]

result = 1
evenlist = number_list[::2]
for num in evenlist:
    result = result * num

How would range(len(list)) be useful here?

like image 890
Ryan Ma Avatar asked Feb 03 '26 10:02

Ryan Ma


1 Answers

Might be something like this, where you reference it using the index of the array;

number_list = [12, 41, 10, 34, 37, 2, 3, 8, 42, 46, 46, 27, 13, 49, 41, 2, 28, 21, 37, 27, 31, 19, 46, 7, 50, 1, 46, 45, 19, 10, 14, 8, 44, 14, 10, 4, 23, 29, 46, 18, 32, 40, 32, 7, 33, 45, 26, 24, 43, 45]

result = 1
for idx in range(0, len(number_list), 2):
   result = result * number_list[idx]
like image 161
fixatd Avatar answered Feb 04 '26 23:02

fixatd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!