I am trying to use the map() function and capitalize all the words in the list.
my_pets = ['sisi', 'bibi', 'titi', 'carla']
def capitalizing(a):
for item in a:
b = item.upper()
return b
print(list(map(capitalizing, my_pets)))
If I run this code, I get the output as following:
['S', 'B', 'T', 'C']
Why is that? Why does the code just runs the first letter and stops for each word?
I already know that the "for" loop/iteration is incorrect to get all the words, I don't need it, but why is this loop runs for the first letter of each word?
Thanks for your assistance in advance.
Your placement of return inside the for loop, causes it to return after the first iteration (on the first character of the string passed to capitalizing). eg:
capitalizing('sisi')
for item in a: # a = 'sisi'
b = item.upper() # item = 's', b = 'S'
return b # b = 'S', return 'S' and exit function
The code can be written more concisely, as the other answers have shown. This code is doing things redundantly.
Here is a fixed version of your code, to return after the for loop is finished building the string, and not after the first iteration:
my_pets = ['sisi', 'bibi', 'titi', 'carla']
def capitalizing(a):
b = ""
for item in a:
b += item.upper()
# using return here will exit the function immediately after the first iteration
return b # return after finishing
print(list(map(capitalizing, my_pets)))