I am trying to add a question mark (?) to the end of each string in a list.
Currently, it is printing ['person?', 'person?', 'person?']
, but I would like it to print ['cat?', 'dog?', 'person?']
.
Could someone please help me figure out what I'm doing wrong?
def suffixQuestionMark(str_list):
'''Returns a list of the same strings but with ? suffixed to each'''
for s in str_list:
str_list = map(lambda x: s + '?', str_list)
return str_list
print (suffixQuestionMark(['cat', 'dog', 'person']))
Thank you!
Returning a list comp would be the simplest solution:
return [s + "?" for s in l]
It is also going to be more efficient than using map.
Your own code you has a lot of potential problems, why you see person?
three times is because you use s
in the lambda so on the last iteration when s
is person, you map all the values to be equal to person + ?
. Even if you changed to map(lambda x: x + '?', str_list)
in the loop you would then get * len(l)
?
added to each string. You would simply return map(lambda x: x + '?', str_list)
but there is no benefit using map in this instance.
You are also not using python 3 as the tag suggests, if you were you would see something like <map object at 0x7fd27a4060f0>
returned not a list of strings.
Use this:
def suffixQuestionMark(str_list):
return map(lambda el: el + '?', str_list)
Output:
['cat?', 'dog?', 'person?']
Here's what was going in your code:
str_list = map(lambda x: s + '?', str_list)
this line executes 3 times (since there are 3 words in the iterated-upon list), overwriting the str_list
at the end of each iteration with the ['word?', 'word?', 'word?']
list, where word
is cat
in the first iteration, and dog
at the second one, and finally person
.
And that's why you end up with the ['person?', 'person?', 'person?']
list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With