Problem with List of List

Fredrik Lundh fredrik at pythonware.com
Sat Aug 26 01:39:54 EDT 2006


Kirt wrote:

> I am a newbie and stuck over this for a week

that's unfortunate.

> I have a code
> ==================CODE=============
> List=[['1', 'a', '6'], ['1', 'b', '6'], ['1', 'c', '6'],
>         ['1', 'd', '6'],['2', 'a','6'], ['2', 'b', '6'],
>         ['2', 'c', '6'], ['2', 'd', '6'], ['3', 'a', '6'],
>         ['3','b', '6'], ['4', 'a', '6'], ['4', 'b', '6']]
> 
> 
> for x in List:
>     temp=[]
>     print x
>     for y in List:
>             if x[0]==y[0]:
>                     print y[0],y[1]
>                     temp.append(y)
>     for z in temp:
>            List.remove(z)
>             print 'rem', z

the for loop uses an internal index to fetch items from the list you're 
looping over, so if you remove items from it, you'll end up skipping 
over items.  this is hinted at in the tutorial:

   http://docs.python.org/tut/node6.html#SECTION006200000000000000000

and explained in further detail in the language reference:

   http://docs.python.org/ref/for.html
   http://pyref.infogami.com/for

</F>




More information about the Python-list mailing list