Here is what is arguably the solution with the least code. >>> a = [12, 12, 1321, 34, 23, 12, 34, 45, 77] >>> list(set(a)-set([12])) [1321, 34, 23, 45, 77]
Cheers --Anand On Thu, Jul 10, 2008 at 5:14 AM, Jeff Rush <[EMAIL PROTECTED]> wrote: > Anand Chitipothu wrote: >> >> On Wed, Jul 9, 2008 at 8:47 PM, Kushal Das <[EMAIL PROTECTED]> wrote: >>> >>> Hi all, >>> >>>>>> a = [12, 12, 1321, 34, 23, 12, 34, 45, 77] >>>>>> for x in a: >>> >>> ... if x == 12: >>> ... a.remove(x) >>>>>> >>>>>> a >>> >>> [1321, 34, 23, 12, 34, 45, 77] >>> >>> Can any one explain me how the remove works and how it is effecting the >>> for >>> loop. > > Others have explained why it fails. Here are two approaches for making it > work, in case you need ideas. > >>>> a = [12, 12, 1321, 34, 23, 12, 34, 45, 77] >>>> filter(lambda x: x != 12, a) > [1321, 34, 23, 34, 45, 77] > > The filter() build-in function is deprecated and the following is the > preferred way of doing it now: > >>>> [x for x in a if x != 12] > [1321, 34, 23, 34, 45, 77] > > Or if your list is quite large and you want to avoid making the new copy of > it, use the new list generator notation: > >>>> b = (x for x in a if x != 12) >>>> for x in b: > ... print x > 1321 > 34 > 23 > 34 > 45 > 77 >>>> list(b) > [1321, 34, 23, 34, 45, 77] > > A list generator performs the filtering just-in-time as you need the > elements. > > -Jeff > _______________________________________________ > BangPypers mailing list > BangPypers@python.org > http://mail.python.org/mailman/listinfo/bangpypers > -- -Anand _______________________________________________ BangPypers mailing list BangPypers@python.org http://mail.python.org/mailman/listinfo/bangpypers