Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add '?' to the end of each string in a list

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!

like image 550
jape Avatar asked Jan 06 '23 08:01

jape


2 Answers

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.

like image 119
Padraic Cunningham Avatar answered Jan 14 '23 19:01

Padraic Cunningham


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.

like image 45
Mohammed Aouf Zouag Avatar answered Jan 14 '23 18:01

Mohammed Aouf Zouag