[Tutor] Comparing to list elements
milgrom at gmail.com
Tue Aug 17 07:41:55 CEST 2004
There's an easier way than list comprehension to find out if an
element is in a list - use the 'in' operator:
if sString in aList:
print 'it's there'
print 'not there'
On Tue, 17 Aug 2004 15:28:18 +1000, Glen Wheeler <gew75 at hotmail.com> wrote:
> I'll present a solution in the form of a list comprehension.
> That way, if you don't know about these, then it incites further education
> >>> aList = [ 'hi', 'hello', 'welcome' ]
> >>> sString = 'goodbye'
> >>> [x for x in aList if x == sString]
> >>> if [x for x in aList if x == sString]:
> ... print "sString is in aList"
> ----- Original Message -----
> From: "Bernard Lebel" <python at bernardlebel.com>
> To: <tutor at python.org>
> Sent: Tuesday, August 17, 2004 7:50 AM
> Subject: [Tutor] Comparing to list elements
> > Hello,
> > I wish to compare a variable value to the elements from a list.
> > For example:
> > aList = [ 'hi', 'hello', 'welcome' ]
> > sString = 'goodbye'
> > Now I want to check if 'goodbye' is present in aList, and if not, take
> > action.
> > Thanks
> > Bernard
More information about the Tutor