Question about usage of two types of for loops..
the task was:
Define a function called product that takes a list of integers as input and returns the product of all of the elements in the list.
For example: product([4, 5, 5]) should return 100 (because 4 * 5 * 5 is 100).
result = lst
for item in range(1,len(lst)):
result *= lst[item]
and that worked fine. BUT, while trying to solve this, i tried some things and was getting some errors, and after some google-ing found this: http://stackoverflow.com/questions/28566577/whats-the-difference-for-item-in-list-and-for-i-in-rangelenlist
this is what bugs me:
`>>> n = [1, 2, 3]
for item in n:
... item *= 2
[1, 2, 3]
but when it's used for item in range:
n = [1, 2, 3]
for i in range(len(n)):
... n[i] *= 2
[2, 4, 6]
is it that item in this case is just local variable and it just returns the value of item in the list and puts it in that local variable 'item'. so when we change 'item' we are not actually changing anything in list, as 'item' variable is just representation of the value under some index in the list?
is that a main difference between those two types of for loops, and can we create some conclusion - if there is some operation to be done on an item from a list, we have to use 'for loop with range', and if we just want to quickly access value under some item and print it out or return it without changing it, then we can use 'for item in list', as somehow easier way..
would appreciate a lot if someone could help me answer this