mccdlibby
mccdlibby

Reputation: 181

Python for() loop with math operators

Say I have a list of numbers such as:

my_list = [1, 17, 2]

And I wanted to add those together. I know I can use print(sum(my_list)). However I wanted to see if there was another way of doing so, so I tried the following:

b = len(my_list)
for m in range(my_list[0], my_list[b-1]):
    m += m
    print(m)

I am sure something like this should work, but I am obviously doing it wrong. The output of this is 2. After I tried:

result = 0
b = len(my_list)
for m in range(my_list[0], my_list[b-1]):
    result = result + m
    print(result)

This outputs 1.

Please explain what I am doing wrong and how I can correct it.

Upvotes: 1

Views: 5499

Answers (6)

Frank Roth
Frank Roth

Reputation: 1

to get the values from my_list you can use this syntax:

for m in my_list:
    print m

If you use range it will give you a range from 1 ( first value of your list ) to 2 (length of your list -1)

To add the values of your list you can try this code:

out = 0
for m in my_list:
   out = out + m
print(out)

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

First, you should put a correct range: 0..2 in your case (since your list items' indexes starts from 0 and has 2 items)

  for i in range(0, b):
      result = result + my_list[i];

Or if you prefer "for each" style you should itterate by list you are summing:

  for m in my_list:
      result = result + m;

Finally if you want to print a final sum only you should correct print indent:

  for m in my_list:
      result = result + m;

  print(result)  # <- mind indent

Wrapping up:

  my_list = [1, 17, 2]

  result = 0

  for m in my_list:
      result = result + m;

  print(result)

Upvotes: 2

Supreet Sethi
Supreet Sethi

Reputation: 1806

Since you are using range function defining range between 1 and 2. The only data generated in m is 1 hence result is 1.

In Python, you can iterate over the elements of a sequence directly:

m = [1, 17, 2]
res = 0
for i in m:
    res += i
print res

Upvotes: 3

Mansur Fattakhov
Mansur Fattakhov

Reputation: 387

from operator import add

my_list = [1, 17, 2]
result=reduce(add, my_list)

Upvotes: 2

Smita K
Smita K

Reputation: 94

try this

my_list = [1, 17, 2]
reduce(lambda x, y: x+y, my_list)

Upvotes: 0

Z3r0n3
Z3r0n3

Reputation: 37

import functools

print(functools.reduce(lambda x,y: x+y, my_list))

Upvotes: 0

Related Questions