Python: Apply Change to Each Item in List

Sorry I’m new to python. I was wondering if there was a faster way to do one small change to each element in a list.

Say I have the following list:

names = ['bob', 'sally', 'robert']

Now say I want to capitalize each element in the list. The only way I can think of to do that is like this:

new_names = []
for name in names:
    first_letter = name[0]
    # if the letter is lowercase, subtract its ascii value by 32 to get the uppercase equivalent
    if ord(first_letter) <= 122 and ord(first_letter) >= 97:
        first_letter = chr(ord(first_letter)-32)
    new_name = first_letter + name[1:]
    new_names.append(new_name)

This gives the desired result, but I was wondering if there was a faster, easier way to do the same thing.

Thanks!

>Solution :

Perhaps the most "Pythonic" way to do this would be to use a list comprehension. Python also has a built in method called capitalize(), which is exactly what you’re looking for.

To put the two together, we can do this:

names = [name.capitalize() for name in names]

What we are doing here is iterating over each name in the names list, and then just changing the first letter to a capital.

Hope this helps!

Leave a Reply