Home > Back-end >  How to calculate numbers in a list?
How to calculate numbers in a list?

Time:11-17

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

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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
  • Related