Convert a Python list with strings all to lowercase or uppercase

Convert a Python list with strings all to lowercase or uppercase

Asked on December 28, 2018 in Python.
Add Comment


  • 3 Answer(s)

    Using list comprehensions:

    This take the form of [function-of-item for item in some-list].

    The below example is used to create a new list where all the items are lower-cased or upper-cased:

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

    With map function:

    >>> map(lambda x:x.lower(),["A","B","C"])
    ['a', 'b', 'c']
    >>> map(lambda x:x.upper(),["a","b","c"])
    ['A', 'B', 'C']
    
    Answered on December 28, 2018.
    Add Comment

    Alternate way with list comprehensions:

    $ 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
    
    Answered on December 28, 2018.
    Add Comment

    Try this simple method:

    >>> map(str.lower,["A","B","C"])
    ['a', 'b', 'c']
    
    Answered on December 28, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.