[Tutor] how to compare elements of 2 lists

Remco Gerlich remco at gerlich.nl
Fri Jan 4 15:19:58 CET 2008


Hi,

a = [4,3,2,6,7,9]
b = [8,6,3,3,2,7]

You can turn this into a list of two element tuples with zip():
>>> zip(a,b)
[ (4,8),(3,6,),(2,3),(6,3),(7,2),(9,7) ]

Now you can loop through that and compare both elements, for instance I
believe this list comprehension is what you're looking for:

[ t[0] < t[1] for t in zip(a,b) ]

but of course we can write that more elegantly with

[ i<j for i,j in zip(a,b) ]

Gives a list of booleans.

Remco Gerlich

On Dec 25, 2007 4:52 PM, sith . <sith618 at yahoo.com> wrote:

> sith . wrote:
> > Hi,
> > I've read the posts on comparing 2 lists and couldn't find the answer to
> > my question.
> > I have 2 lists
> > a = [4,3,2,6,7,9]
> > b = [8,6,3,3,2,7]
> > How can I determine if the elements in a are larger or smaller than the
> > elements in b.
> >
> > for i in a:
> >     for u in b:
> >         i > u
> > does not return the result I seek.
> >
> > In this example, 4 from a is compared to 8,6,3,3,2,7 then 3 from a is
> > compared to all the elements in b.
> > I'd like
> > 4 to 8,
> > 3 to 6,
> > 2 to 3 and so on; like 2 columns in excel, the third column would be a
> > new list of boolean values.
> > Can someone help please?  Thank you.
> >
> all(all(i>j for j in b) for i in a)
> HTH
>
>
> Hi,
> Thanks for your reply.  This is what I get:
> >>> a = [4,3,2,6,7,9]
> >>> b = [8,6,3,3,2,7]
> >>> all(all(i>j for j in b) for i in a)
> >>> all(all(i>j for j in b) for i in a)
> False
> How do I make it loop through the whole list?
>
> ------------------------------
> Never miss a thing. Make Yahoo your homepage.<http://us.rd.yahoo.com/evt=51438/*http://www.yahoo.com/r/hs>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080104/05dc4470/attachment.htm 


More information about the Tutor mailing list