How to Convert a List of Strings to Uppercase in Python?

In Python, you can make all strings in a list of strings uppercase by calling the upper() method on every element of the list, for example, using list comprehension, like so:

items = ['foo', 'Bar', 'bAz']
new_list = [item.upper() for item in items]

print(new_list) # ['FOO', 'BAR', 'BAZ']

The code above would create a new list with all strings in the list in uppercase. This is equivalent to the following, which uses map():

items = ['foo', 'Bar', 'bAz']
new_list = list(map(lambda item: item.upper(), items))

print(new_list) # ['FOO', 'BAR', 'BAZ']

However, using list comprehension provides a more readable and concise syntax. For that reason, it is generally preferred and would be the recommended way.

For completeness sake, you can also achieve the same result with a simple for..in loop:

items = ['foo', 'Bar', 'bAz']
new_list = []

for item in items:
    new_list.append(item.upper())

print(new_list) # ['FOO', 'BAR', 'BAZ']

However, it might not be the best choice as it would create/overwrite a variable named "item", which would persist even after the loop completes:

items = ['foo', 'Bar', 'bAz']
new_list = []

for item in items:
    new_list.append(item.upper())

print(item) # 'bAz'

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.