Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: check if value is in a list no matter the CaSE

Tags:

python

loops

I want to check if a value is in a list, no matter what the case of the letters are, and I need to do it efficiently.

This is what I have:

if val in list:

But I want it to ignore case

like image 304
neolaser Avatar asked Mar 20 '11 22:03

neolaser


3 Answers

check = "asdf"
checkLower = check.lower()

print any(checkLower == val.lower() for val in ["qwert", "AsDf"])

# prints true

Using the any() function. This method is nice because you aren't recreating the list to have lowercase, it is iterating over the list, so once it finds a true value, it stops iterating and returns.

Demo : http://codepad.org/dH5DSGLP

like image 171
Mike Lewis Avatar answered Nov 03 '22 06:11

Mike Lewis


If you know that your values are all of type str or unicode, you can try this:

if val in map(str.lower, list):
...Or:
if val in map(unicode.lower, list):
like image 35
mjbommar Avatar answered Nov 03 '22 05:11

mjbommar


If you really have just a list of the values, the best you can do is something like

if val.lower() in [x.lower() for x in list]: ...

but it would probably be better to maintain, say, a set or dict whose keys are lowercase versions of the values in the list; that way you won't need to keep iterating over (potentially) the whole list.

Incidentally, using list as a variable name is poor style, because list is also the name of one of Python's built-in types. You're liable to find yourself trying to call the list builtin function (which turns things into lists) and getting confused because your list variable isn't callable. Or, conversely, trying to use your list variable somewhere where it happens to be out of scope and getting confused because you can't index into the list builtin.

like image 2
Gareth McCaughan Avatar answered Nov 03 '22 05:11

Gareth McCaughan