Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading