Simple - looking for a way to do an element exists check..
BjornSteinarFjeldPettersen at gmail.com
Sun Feb 24 02:19:47 CET 2008
On Feb 23, 6:18 pm, Paul Hankin <paul.han... at gmail.com> wrote:
> On Feb 22, 7:01 pm, Paul McGuire <pt... at austin.rr.com> wrote:
> > On Feb 22, 12:54 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> > > Paul Rubin <http://phr...@NOSPAM.invalid> writes:
> > > > if any(x==element for x in a):
> > > > a.append(element)
> > > Should say:
> > > if any(x==element for x in a):
> > > a.append(element)
> > I think you have this backwards. Should be:
> > if not any(x==element for x in a):
> > a.append(element)
> IMO Jason's solution of testing containment in a generator is better
> (more readable).
> if element not in (x for x in a):
> Paul Hankin
It may be more readable (although that's debatable), but it always
traverses the entire list.
If the list is short I'd use either the traditional "for/else" or the
newer "if all(...)":
if all(x != element for x in a):
which allows for short-circuit evaluation -- I generally try to stay
away from negating any() and all() because the logic often gets
If the lists are long enough to care, either rewrite use a set-based
solution if the items are hashable, or keep the elements sorted and
rewrite to use the bisect module if the elements can be ordered.
More information about the Python-list