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!