NervousDev
NervousDev

Reputation: 87

How to calculate numbers in a list?

I have to add every number with one behind it in the list using loops or functions

example text;

list[1,2,3] => (1+3)+(2+1)+(3+2) 

output = 12

example code;

myList = [1,2,3]
x = myList [0] + myList [2]
x = x + (myList [1]+myList [0])
x = x + (myList [2]+myList [1])
print(x) # 12

I dont want to calculate them using sum() or just like 1+2+3

Upvotes: 0

Views: 304

Answers (3)

Abdul Gaffar
Abdul Gaffar

Reputation: 390

Try accessing the list index and value using enumerate function

>>> [x+mylist[i-1] for i, x in enumerate(mylist)]
[4, 3, 5]

To get the sum of the result

>>> sum([x+mylist[i-1] for i, x in enumerate(mylist)])
12

Upvotes: 0

Barmar
Barmar

Reputation: 781210

Loop through the list, adding the element and the element before it to the total. Since list indexing wraps around when the index is negative, this will treat the last element as before the first element.

total = 0
for i in range(len(myList)):
    total += myList[i] + myList[i-1]
print(total)

Upvotes: 1

Jay
Jay

Reputation: 2471

In python, list[-1] returns the last element of the list so doing something like this should do the job -

myList = [1,2,3]
total = 0
for i, num in enumerate(myList):
    print(num, myList[i-1])
    total += num + myList[i-1]
print(total)

Output:

1 3
2 1
3 2
12

Upvotes: 1

Related Questions