Reputation: 5690
Very basic question here (I've just started with Python).
I have a list object. It contains five numbers [3,6,2,3,1]
I want find the sum of the first, third and fourth numbers in the list.
What is the syntax?
Upvotes: 0
Views: 4861
Reputation: 94475
You can for instance sum elements #1, #3, and #4 with the flexible expression
sum(my_list[i] for i in (0, 2, 3))
The index of the first element is 0 [not 1], etc., i.e. my_list[0]
is the first element (with value 3, in the original question), etc.
Upvotes: 7
Reputation: 33161
You can access an element of a Python list by index by appending [list_index]
to the list object (replace list_index
with the index you want). For example:
my_list_object = [3,6,2,3,1]
my_sum = my_list_object[0]+my_list_object[2]+my_list_object[3]
Upvotes: 1
Reputation: 601479
The items of a list are numbered like this:
a = [3, 6, 2, 3, 1]
^ ^ ^ ^ ^
index 0 1 2 3 4
To access the item with the index i
, use a[i]
. From here, you should be able to figure out how to sum the desired items.
Upvotes: 6