why for loop print only once after add if statement

Steven D'Aprano steve at pearwood.info
Sat May 28 08:02:59 EDT 2016


On Sat, 28 May 2016 08:19 pm, jobmattcon at gmail.com wrote:

> for item, i in enumerate(aa)
>   print item

Wrong way around. It should be:

for i, item in enumerate(aa):
    print item

For example:

py> for i, item in enumerate(aa):
...     print i, item
...
0 c
1 h
2 e
3 e
4 s
5 e


> this writing, it can print all values
> 
> for item, i in enumerate(aa)
>   if item == findit:
>     print item
> 
> this only print the first value, means it only print once then not print
> again,

No, it doesn't not print the first value, it prints any value that equals
findit, whatever that is. If nothing equals findit, nothing will be
printed. Only items which equal findit will be printed.


py> findit = 'z'
py> for i, item in enumerate(aa):
...     if item == findit:
...             print i, item
...
py> findit = 'e'
py> for i, item in enumerate(aa):
...     if item == findit:
...             print i, item
...
2 e
3 e
5 e


-- 
Steven




More information about the Python-list mailing list