How to calculate numbers in a list?
Question:
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
Answers:
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
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)
Try accessing the list index and value using enumerate function
>>> [x+mylist[i-1] for i, x in enumerate(mylist)]
[4, 3, 5]
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
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
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)
Try accessing the list index and value using enumerate function
>>> [x+mylist[i-1] for i, x in enumerate(mylist)]
[4, 3, 5]