On Wed, 22 Dec 2004 14:59:32 -0500, Mike C. Fletcher
<[EMAIL PROTECTED]> wrote:

[snip]

>
> Probably the most pythonic approach to this problem when dealing with
> small lists is this:
>
>    result = [ item for item in source if item != 'e' ]
>
> or, if you're using an older version of Python without list comprehensions:
>
>    filter( lambda item: item!='e', source )
>

I believe lamda's are unnamed functions aren't they?? Still learning... ;-)

> or even (expanding the list comprehension):
>
>    result = []
>    for item in source:
>       if item != 'e':
>          result.append( item )
>
> The "python"-ness of the solutions is that we are using filtering to
> create a new list, which is often a cleaner approach than modifying a
> list in-place.  If you want to modify the original list you can simply
> do source[:] = result[:] with any of those patterns.
>

yeah actually i saw what Fedrik had to say above. I created a sliced
copy of the l & did my homework within the for loop

>>> l
['a', 'b', 'c', 'd', 'e']
>>> for x in l[:]:
       if x == 'd':
               l.remove('d');

>>> l
['a', 'b', 'c', 'e']

This code is so clean and looks very healthy. :) Python will live a
long way because its a cute language. :-)

> If you really do need/want in-place modification, these patterns are
> quite serviceable in many instances:
>
>    # keep in mind, scans list multiple times, can be slow
>    while 'e' in source:
>       source.remove('e')
>
> or (and this is evil C-like code):
>
>    for index in xrange( len(source)-1, -1, -1 ):
>       if source[i] == 'e':
>          del source[i]
> 
thanx Mike, i have tried this C-ish way as well . :-) it seemed quiete
ok for my  small list but dont know about huge lists.

> Keep in mind that, in the presence of threading, any index-based scheme
> is likely to blow up in your face (even the filtering solutions can
> produce unexpected results, but they are generally not going to raise
> IndexErrors due to off-the-end-of-the-list operations).
>

Every 2-4 hours i check the c.l.py ... Its so nice that i learn new
things everyday in this list.. (some are goood but some are extremely
subjective!!)
Lastly i personally feel that Python's way of trying things out before
implementing is really healthy way of programming. Especially towards
XP oriented projects. :-)

Thanks Fredrik and Mike.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to