how to explain such codes, python's bug or mine?

Jim jbo at cannedham.ee.ed.ac.uk
Wed Apr 13 06:18:10 EDT 2005


MaHahaXixi wrote:
>>>>j = range(20)
>>>>print j
> 
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
> 
>>>>for k in j:
> 
>  if k <= 10:
>   j.remove(k)
> 
> 
> 
>>>>print j
> 
> [1, 3, 5, 7, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19]
> 
> 
> 
> Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on
> win32
> Type "copyright", "credits" or "license()" for more information.
> 
> i think python do convert there codes to such style:
> for (i = 0; i < len(j); i++)
>    k = j[i]
>    ......

> what do u think?
> 
> 

I'm not quite sure of your question but with the second style you're not 
attempting to change the original list but make a copy. That's perfectly 
easy to do in Python as it is. The exampmle is a cautionary one about 
changing the list on which you are iterating.

Jim



More information about the Python-list mailing list