0

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?

1

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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.

Comments

3

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])

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.