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 ?
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).
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.
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.
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.
if any(s.lower() == "foo" for s in list): print "found"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With