[ACCEPTED]-Python: check if value is in a list no matter the CaSE-loops

Accepted answer
Score: 16
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 4 because you aren't recreating the list to 3 have lowercase, it is iterating over the 2 list, so once it finds a true value, it 1 stops iterating and returns.

Demo : http://codepad.org/dH5DSGLP

Score: 4

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

if val in map(str.lower, list):
...Or:
if val in map(unicode.lower, list):
Score: 2

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

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

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

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

Score: 0

You can lower the values and check them:

>>> val
'CaSe'
>>> l
['caSe', 'bar']
>>> val in l
False
>>> val.lower() in (i.lower() for i in l)
True

0

Score: 0
items = ['asdf', 'Asdf', 'asdF', 'asjdflk', 'asjdklflf']
itemset = set(i.lower() for i in items)

val = 'ASDF'
if val.lower() in itemset:  # O(1)
    print('wherever you go, there you are')

0

More Related questions