Generator in if-statement in python

Or how to make an if-statement in a modified list.

I read StackOverflow for a while (thanks everyone). I love it. I also saw that you can ask a question and answer it yourself. Sorry if I duplicate, but I did not find this specific answer in StackOverflow.


  • How do you check if an item is in the list, but change it at the same time?

My problem:

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

As I do not know the case of an element in the list, I want to compare it with lowercase. The obvious but ugly answer would be the following:

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

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

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

Can I do it better?

+5
source share
5 answers
if any(s.lower() == "foo" for s in list): print "found"
+8

:

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

- if "foo" in lowerlist if "foo" in [item.lower() for item in mylist]

+1

:

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

:

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

if "foo" in lowerCaseSet:
   print "found"

BTW. list, list.

0

, , , , :

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'
0

All Articles