Convert a list with strings all to lowercase or uppercase
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Island
--
Chapters
00:00 Question
00:23 Accepted answer (Score 616)
00:43 Answer 2 (Score 67)
01:09 Answer 3 (Score 67)
01:19 Answer 4 (Score 21)
01:46 Thank you
--
Full question
https://stackoverflow.com/questions/1801...
Accepted answer links:
[list comprehensions]: https://docs.python.org/3/tutorial/datas...
[map]: https://docs.python.org/3/library/functi...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Island
--
Chapters
00:00 Question
00:23 Accepted answer (Score 616)
00:43 Answer 2 (Score 67)
01:09 Answer 3 (Score 67)
01:19 Answer 4 (Score 21)
01:46 Thank you
--
Full question
https://stackoverflow.com/questions/1801...
Accepted answer links:
[list comprehensions]: https://docs.python.org/3/tutorial/datas...
[map]: https://docs.python.org/3/library/functi...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list
#avk47
ACCEPTED ANSWER
Score 672
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']
ANSWER 2
Score 77
>>> list(map(str.lower,["A","B","C"]))
['a', 'b', 'c']
ANSWER 3
Score 68
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
ANSWER 4
Score 22
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
Type "help", "copyright", "credits" or "license" for more information.
>>> 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']