Search code examples
pythonlistfor-looprange

How do I include the last element in a range in python?


I am using a for loop to add all the elements in a list but when I index (x[-1]) the last element, it still not included. Ex:

x=[3,4,5,6]
total=0
for i in range(x[0],x[-1]):
    total= total + i
print(total)

The answer I am looking for is 18 but when I run it, it returns 12. (It is still not including the last element). I understand the range function does that but is there a way to still include the last element? Do I have to use a different function? What am I doing wrong?


Solution

  • Using your code:

    x=[3,4,5,6]
    total=0
    for i in x:
        total= total + i
    print(total)