For loops in Python are baffling to a VBA programmer.
NumLst = [8, 1, 3, 2]
for I in NumLst:
print (I, end = ' ')
Output from this is
8 1 3 2
Not what I expected. I thought was asking Python to print the loop counter, not the contents of the loop.
I expected 0 1 2 3
Thought maybe `enumerate’ would get the result I expected. And it does - Kind of.
NumLst = [8, 1, 3, 2]
for I in enumerate (NumLst):
print (I)
This code gives us
(0, 8)
(1, 1)
(2, 3)
(3, 2)
So it does print the loop counter, even if still not what I had in mind.
But all of the above is immaterial. I got sidetracked on trying to grasp for loops because I was unable to do what I originally set out to do. I wanted
to replace one or more of the values in NumLst with a different value. Tried this code:
for I in enumerate (NumLst):
NumLst [I] = NumLst [I] + 1
print (I)
print (NumLst)
I expected
9
2
4
3
Instead I got:
Traceback (most recent call last):
File “C:/Users/Sam/AppData/Local/Programs/Python/Python39/Python OutPut/Prac 02.Py”, line 50, in
NumLst [I] = NumLst [I] + 1
TypeError: list indices must be integers or slices, not tuple
Well, the list indices ARE integers. Aren’t they??
So once more I’m asking you guys to point me in the right direction.