0

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.

I want to be able to apply any function to each element in a list.

Thanks!

Edit:

I ended up going with the following:

names = ['bill', 'James']
new_names = [(chr(ord(x[0])-32)*(97<=ord(x[0])<=122)or x[0])+x[1:]for x in names]

Thank you to Toranian for suggesting list comprehensions!

Ethan Posner
  • 343
  • 1
  • 2
  • 14
  • Research [list comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions). It helps to know what they are called – Mark Tolonen Jun 23 '22 at 22:25
  • Try this - `[name.capitalize() for name in names]` maybe? As @MarkTolonen suggested List Comp. is faster way. – Daniel Hao Jun 23 '22 at 22:25
  • There are two ways: create a new list element by element, or use `for i in range(len(names)):`. – Tim Roberts Jun 23 '22 at 22:26
  • I wanted to know how to apply a function to every element in a list. The capitalization was just an example of something i might want to do. – Ethan Posner Jun 23 '22 at 23:56

3 Answers3

2

Python has a built-in str.capitalize() method that does this. You can use it in a list comprehension.

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

There's also a similar method str.title(), which capitalizes each word in the string, not just the first letter of the string.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Use enumerate, which gives the index and the item:

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

for i, name in enumerate(names):
    names[i] = name[0].upper() + name[1:]

print(names)

which gives:

['Bob', 'Sally', 'Robert']

Here, I've used upper(). But Barmar's answer of capitalize/title is even better.

bfris
  • 5,272
  • 1
  • 20
  • 37
1

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!

Toranian
  • 54
  • 2