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

Time:10-15

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?

CodePudding user response:

these are three solutions for your usage

    x=[3,4,5,6]
    total=0

    #solution 1 :
    total =sum(x)

    #solution 2
    for i in x:
        total= total   i
    print(total)

    #solution 3
    for i in range(0,len(x)):
        total= total   x[i]
    print(total)

CodePudding user response:

Using your code:

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