In this tutorial, we will learn how to capitalize the first letter of each item in a list using Python programming language.
After going through this tutorial, you will be able to easily capitalize the first letter of each item in a list no matter the size of the list or data type of the list items. Let’s get started!
Step 1: Create a Python list
For the purpose of this tutorial, let’s create a list named fruits
containing various fruit names in lowercase.
1 |
fruits = ["apple", "banana", "cherry", "dates", "fig", "kiwi"] |
Step 2: Use the list comprehension method
List comprehension is an elegant and concise way to create a new list from an existing list in Python. We will use the list comprehension method to capitalize the first letter of each item in the fruits
list. To do this, we call the str.capitalize()
method on each item while looping through the list.
1 |
capitalized_fruits = [item.capitalize() for item in fruits] |
Step 3: Print the output
Let’s print the output of the capitalized list to see the result of our list comprehension.
1 |
print(capitalized_fruits) |
When you run the code, you should see the output below:
['Apple', 'Banana', 'Cherry', 'Dates', 'Fig', 'Kiwi']
Step 4: Use the map() function and lambda function
Another way to achieve this is by using the map()
function along with a lambda function. The map()
function applies a given function to all items in an input list and returns an iterator. In our case, we will use the lambda function to capitalize the first letter of each item in the fruits
list.
1 |
capitalized_fruits_map = map(lambda item: item.capitalize(), fruits) |
To see the result, we need to convert the iterator object returned by the map()
function into a list and print it.
1 |
print(list(capitalized_fruits_map)) |
The output should be identical to the one we got using the list comprehension method:
['Apple', 'Banana', 'Cherry', 'Dates', 'Fig', 'Kiwi']
The complete code
1 2 3 4 5 6 7 8 9 |
fruits = ["apple", "banana", "cherry", "dates", "fig", "kiwi"] # Using list comprehension capitalized_fruits = [item.capitalize() for item in fruits] print(capitalized_fruits) # Using map() function and lambda function capitalized_fruits_map = map(lambda item: item.capitalize(), fruits) print(list(capitalized_fruits_map)) |
Conclusion
In this tutorial, we learned how to capitalize the first letter of each item in a list using Python programming language.
We used two different methods to achieve this – the list comprehension method and the map()
function with a lambda function.
Both methods work effectively and you can choose the one that you find most convenient or suitable for your use case.