find the index of a string ignoring cases

you can ignore the cases by converting the total list and the item you want to search into lowercase.

>>> to_find = 'MG'
>>> old_list =  ['ADMISSION' ,'Colace','100','mg', 'b.i.d.' , 'insulin','Lente','12']
>>> new_list = [item.lower() for item in old_list]
>>> new_list.index(to_find.lower())
3

One of the more elegant ways you can do this is to use a generator:

>>> list = ['ADMISSION' ,'Colace','100','mg', 'b.i.d.' , 'insulin','Lente','12']
>>> next(i for i,v in enumerate(list) if v.lower() == 'mg')
3

The above code makes a generator that yields the index of the next case insensitive occurrence of mg in the list, then invokes next() once, to retrieve the first index. If you had several occurrences of mg in the list, calling next() repeatedly would yield them all.

This also has the benefit of being marginally less expensive, since an entire lower cased list need not be created; only as much of the list is processed as needs to be to find the next match.

Tags:

Python