Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


  • How do you verify if a element is in a list but modify it in the same time?

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 ?

like image 743
Philippe Lavoie Avatar asked Aug 05 '10 21:08

Philippe Lavoie


People also ask

What is generator in Python with example?

Python generators are a simple way of creating iterators. All the work we mentioned above are automatically handled by generators in Python. Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).

What is generator expression in Python?

A generator expression is an expression that returns a generator object. Basically, a generator function is a function that contains a yield statement and returns a generator object.

Is range a generator?

range is a built-in generator, which generates sequences of integers. Reading Comprehension: Using ``range``: Using range in a for-loop, print the numbers 10-1, in sequence.

How do generators work Python?

A Python generator is a function that produces a sequence of results. It works by maintaining its local state, so that the function can resume again exactly where it left off when called subsequent times. Thus, you can think of a generator as something like a powerful iterator.


1 Answers

if any(s.lower() == "foo" for s in list): print "found"
like image 180
Wai Yip Tung Avatar answered Oct 02 '22 23:10

Wai Yip Tung