Convert a list with strings all to lowercase or uppercase Convert a list with strings all to lowercase or uppercase python python

Convert a list with strings all to lowercase or uppercase


It can be done with list comprehensions

>>> [x.lower() for x in ["A", "B", "C"]]['a', 'b', 'c']>>> [x.upper() for x in ["a", "b", "c"]]['A', 'B', 'C']

or with the map function

>>> list(map(lambda x: x.lower(), ["A", "B", "C"]))['a', 'b', 'c']>>> list(map(lambda x: x.upper(), ["a", "b", "c"]))['A', 'B', 'C']


Besides being easier to read (for many people), list comprehensions win the speed race, too:

$ python2.6 -m timeit '[x.lower() for x in ["A","B","C"]]'1000000 loops, best of 3: 1.03 usec per loop$ python2.6 -m timeit '[x.upper() for x in ["a","b","c"]]'1000000 loops, best of 3: 1.04 usec per loop$ python2.6 -m timeit 'map(str.lower,["A","B","C"])'1000000 loops, best of 3: 1.44 usec per loop$ python2.6 -m timeit 'map(str.upper,["a","b","c"])'1000000 loops, best of 3: 1.44 usec per loop$ python2.6 -m timeit 'map(lambda x:x.lower(),["A","B","C"])'1000000 loops, best of 3: 1.87 usec per loop$ python2.6 -m timeit 'map(lambda x:x.upper(),["a","b","c"])'1000000 loops, best of 3: 1.87 usec per loop


>>> list(map(str.lower,["A","B","C"]))['a', 'b', 'c']


matomo