Philippe Lavoie
Philippe Lavoie

Reputation: 2593

Generator in if-statement in python

Or How to if-statement in a modified list.

I've been reading StackOverflow for a while (thanks to everyone). I love it. I also seen that you can post a question and answer it yourself. Sorry if I duplicate, but I didn't found this particular answer on StackOverflow.


My problem:

myList = ["Foo", "Bar"]
if "foo" in myList:
  print "found!"

As I don't know the case of the element in the list I want to compare with lower case list. The obvious but ugly answer would be:

myList = ["Foo", "Bar"]
lowerList = []

for item in myList:
  lowerList.append(item.lower())

if "foo" in lowerList:
  print "found!"

Can I do it better ?

Upvotes: 5

Views: 8473

Answers (5)

Tim McNamara
Tim McNamara

Reputation: 18375

This combines the memory advantages of a generator expression with the speed gains from removing duplicates:

if "foo" in (s.lower() for s in set(list)): print "found"

Upvotes: 0

Tony Veijalainen
Tony Veijalainen

Reputation: 5555

Please do not use list as variable name, here is version which puts generator to variable and demonstrates, that generation stopped after finding the answer and did not exhaust the generator:

list_to_search = ["Foo", "Bar"]
lowergen = (item.lower() for item in list_to_search)
if "foo" in lowergen:
  print "found!"
print next(lowergen), 'is next after it'

Upvotes: 0

Wai Yip Tung
Wai Yip Tung

Reputation: 18754

if any(s.lower() == "foo" for s in list): print "found"

Upvotes: 8

Piotr Czapla
Piotr Czapla

Reputation: 26522

How about:

theList = ["Foo", "Bar"]
lowerCaseSet = set(x.lower for x in theList)

if "foo" in lowerCaseSet:
   print "found"

BTW. you shouldn't call your variable list as this word is already used by list type.

Upvotes: 0

Jason Scheirer
Jason Scheirer

Reputation: 1698

List comprehensions:

mylist = ["Foo", "Bar"]
lowerList = [item.lower() for item in mylist]

Then you can do something like if "foo" in lowerlist or bypass the temporary variable entirely with if "foo" in [item.lower() for item in mylist]

Upvotes: 1

Related Questions