CaptainProg
CaptainProg

Reputation: 5690

Python: access list value by reference

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

Answers (4)

Eric O. Lebigot
Eric O. Lebigot

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

Jack Edmonds
Jack Edmonds

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

Sven Marnach
Sven Marnach

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

phihag
phihag

Reputation: 287775

Just write the index in brackets. Note that the index starts with zero:

lst[0] + lst[2] + lst[3]

In some cases, you can use the sum function and select a slice of the list. For example, to get the sum of the first, third, and fifth element, use:

sum(lst[::2])

Upvotes: 3

Related Questions