How to Convert the First Letter of Each Item in a List to Uppercase in Python?

Estimated read time 2 min read

To convert the first letter of each item in a list to uppercase in Python, you can use list comprehension or a loop. Here are examples using both approaches:

Using list comprehension:

my_list = ['apple', 'banana', 'cherry']

# Using list comprehension
modified_list = [item.capitalize() for item in my_list]

print(modified_list)

Using a loop:

my_list = ['apple', 'banana', 'cherry']

# Using a loop
modified_list = []
for item in my_list:
    modified_list.append(item.capitalize())

print(modified_list)

In both examples, we have a list called my_list with lowercase words. We iterate over each item in the list and use the capitalize() method to convert the first letter of each item to uppercase.

The first example uses list comprehension, where we create a new list modified_list by applying the capitalize() method to each item in my_list in a single line of code.

The second example uses a loop to iterate over my_list. Inside the loop, we use the append() method to add the modified item (with the first letter capitalized) to the modified_list.

After running either of the code examples, the modified_list will contain the items from my_list with the first letter of each item converted to uppercase.

Note that the capitalize() method converts only the first letter to uppercase and leaves the rest of the letters as lowercase. If you want to capitalize all letters in each item, you can use the title() method instead.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply