In Python, you can make all strings in a list of strings lowercase by calling the lower()
method on every element of the list, for example, using list comprehension, like so:
items = ['FOO', 'Bar', 'bAz'] new_list = [item.lower() 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 lowercase. This is equivalent to the following, which uses map()
:
items = ['FOO', 'Bar', 'bAz'] new_list = list(map(lambda item: item.lower(), 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.lower()) 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.lower()) 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.