0

I have a list of numbers , and I want to add up the numbers, but I don't want to add all the numbers from the list, just the selected numbers, like the first three.

list = [2, 3, 7, 11, 15, 21]
for i in list:
   sum += i

My code obviously adds up all the numbers from the list. I've tried changing the for loop to in range(0,4) but that just added together numbers 0, 1, 2, 3 and not the numbers from my list. So how can I modify my code to add up the first three numbers from my list.

patorikku
  • 113
  • 4
  • 11

2 Answers2

6

You could slice your list...

list[0:3]

You could do it like...

sum(list[0:3])

It also appears you don't need the start 0 there.

Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
  • 2
    +1 for using the `sum()` builtin. No need to reinvent the wheel. That said, it might be worth noting `list` is a bad variable name, and you can leave out the first index when it's `0`. – Gareth Latty Feb 03 '13 at 02:28
  • @Lattyware Good point on the variable name, and I added the note about the optional `0`. – alex Feb 03 '13 at 02:30
  • @alex And what if I want to add random numbers (not in sequence) from my list, like the first, second, fourth and sixth number. – patorikku Feb 03 '13 at 02:54
3

You need to iterate through the first three elements of your list. You can do this using list slicing

total = 0
for i in lst[:3]:
    total += i

As a side note, don't name your variables list or sum as they will override the built in type/function and could cause problems down the track.

Community
  • 1
  • 1
Volatility
  • 31,232
  • 10
  • 80
  • 89