Dumb Stupid Question About List and String

MRAB python at mrabarnett.plus.com
Tue Aug 31 15:42:55 EDT 2010


On 31/08/2010 20:20, Alban Nona wrote:
> Ok, here a solution:
>
> myFirstList = ["FN067_098_MEN", "FN067_098_JIN", "FN067_098_BG"]
>
> mySecondList =
> ["FN067_098_MEN_Hair_PUZ_v001.0001.exr","FN067_098_JIN_Hair_SPC_v001.0001.exr","FN067_098_MEN_Jin_MVE_v001.0001.exr","FR043_010_GEN_NRM_v001.0001.exr"]
>
> for n in myFirstList:
>       var = str(n)

Why str(n)?

Also, it would be clearer if you used different variables for the
different loops.

>       for n in mySecondList:
>           if var in n:
>                mySecondList.remove(n)

You shouldn't change the length of a list over which you're iterating. 
Python will step along the list one entry at a time and won't notice 
when you remove an entry, so the next one will be skipped. For example:

 >>> letters = ["a", "b", "c", "d", "e"]
 >>> for i in letters:
...     if i == "b" or i == "c":
...         letters.remove(i)
...
 >>> print letters
['a', 'c', 'd', 'e']

It removed "b" and then moved on to the next entry, which is "d"
because "b" has been removed and all the following entries have moved
down one place. It never sees "c".

>
> print mySecondList
>
[snip]



More information about the Python-list mailing list