Python Forum

Full Version: for loops break when I call the list I'm looping through
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
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
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.
'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!
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