I'm new to programming and I'm not sure how to do this. I have the following list:
marbles_in_bucket = [1, 1, 1, 1, 1, 1]
And I want to add, say, the value of index 1 to the value of index 2 to get 2. I tried to do this by writing marbles_in_bucket[1 + 2]
but I got IndexError: list index out of range
. How would I go about this?
> marbles_in_bucket[1] + marbles_in_bucket[2]
2
You can also index with ranges like:
> sum(marbles_in_bucket[1:3]) # the end index is exclusive
2
Following should do it.
marbles_in_bucket[1] + marbles_in_bucket[2]
If you are running that in a loop and iterating till the end you may need to check that you don't overrun the list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.