David542
David542

Reputation: 110209

Case-insensitive IN for python

Is there a way to do a SQL-like IN statement in python. For example:

'hello' in ['Hello', 'Goodbye'] # case insensitive
True

I was thinking a list comprehension to rebuild the list, but hopefully there is something much simpler.

Upvotes: 1

Views: 937

Answers (2)

user2555451
user2555451

Reputation:

You can map the list to str.lower:

if 'hello' in map(str.lower, ['Hello', 'Goodbye']):

In Python 3.x, this will not build a new list since map returns an iterator. In Python 2.x, you can achieve the same by importing itertools.imap.


Alternately, you could just use a generator expression:

if 'hello' in (x.lower() for x in ['Hello', 'Goodbye']):

This is lazy too and works the same in both versions.

Upvotes: 5

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

A generator expression using any would be one of the more efficient ways, it will lazily evaluate short circuiting if we find a match:

l =['Hello', 'Goodbye'] 
s = "hello"
if any(s == x.lower() for x in l):
    ....

In [10]: l =['Hello', 'Goodbye']   
In [11]: s = "hello"    
In [12]: any(s == x.lower() for x in l)
Out[12]: True

Upvotes: 3

Related Questions