# Toggle between lowercase and uppercase in a list of strings.

## Problem

I’ve got a Python list variable with strings in it. Is there a function that can change all strings to lowercase in one pass and vice versa?

## Solution #1

It’s possible to do it 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 by using the map feature

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

## Solution #2

List comprehensions win the speed race as well as being easier to read (for many people):

``````\$ 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
``````

## Solution #3

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

## Solution #4

List comprehension is how I’d do it, it’s the “Pythonic” way. The following transcript shows how to convert a list to all upper case then back to lower:

``````pax@paxbox7:~\$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux

>>> x = ["one", "two", "three"] ; x
['one', 'two', 'three']

>>> x = [element.upper() for element in x] ; x
['ONE', 'TWO', 'THREE']

>>> x = [element.lower() for element in x] ; x
['one', 'two', 'three']
``````

## Solution #5

For this sample the comprehension is fastest

``````\$ python -m timeit -s 's=["one","two","three"]*1000' '[x.upper for x in s]'
1000 loops, best of 3: 809 usec per loop

\$ python -m timeit -s 's=["one","two","three"]*1000' 'map(str.upper,s)'
1000 loops, best of 3: 1.12 msec per loop

\$ python -m timeit -s 's=["one","two","three"]*1000' 'map(lambda x:x.upper(),s)'
1000 loops, best of 3: 1.77 msec per loop
``````