Python Forum
for loops break when I call the list I'm looping through - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: for loops break when I call the list I'm looping through (/thread-40750.html)



for loops break when I call the list I'm looping through - Radical - Sep-17-2023

I was trying out the for loops in Python, and I don't fully understand why it breaks.

When I type:

for i in catNames:
    print(catNames[i])
the program breaks.

but when I type:

for i in catNames:
    print(i)
I get the desired result.

I also found out I can do:

for i in range(len(catNames)):
    print(catNames[i])
for the same successful result.

So what is the key difference here? Why does the first option break the program?


RE: for loops break when I call the list I'm looping through - buran - Sep-17-2023

In python for loop iterates over list elements, not their indices. The working one (the second example) should be clear enough to understand that and answer the question yourself.
The last one is considered anti-pattern and should not be not used


RE: for loops break when I call the list I'm looping through - deanhystad - Sep-18-2023

In the first example the iterable is a list, so i is a list value, not an index. You have no index, so you cannot index. In the third example the iterable returns ints. You can index using an int value.


RE: for loops break when I call the list I'm looping through - Pedroski55 - Sep-18-2023

'i' tends to suggest an index number, but if you don't have an index number, an integer, or a range of integers, you can't access list elements by index.

Maybe better not to use 'i' in that case, use something like 'name' as it is more "human readable" is the phrase, I believe:

for name in pussyNames:
    print('Here', name, 'here')
But if you need a index number, well, you have already done that!


RE: for loops break when I call the list I'm looping through - buran - Sep-18-2023

Just to mention that if you need (for whatever reason) both index and element/value, the canonical way to do it is using enumerate
names = ['John', 'Jane', 'Marc']
for idx, name in enumerate(names, start=1): # start from 1, default is 0
    print(f'{idx}. {name}')
output
Output:
1. John 2. Jane 3. Marc