Search code examples
pythonpython-3.xlist-comprehensionmap-function

Adding sentence breaks to the beginning and end of each element in a list


I have a list of strings:

mini_corpus = ['I am Sam','Sam I am','I am Sam','I do not like green eggs and Sam']

I need to add a sentence boundary at the beginning and end of each element (i.e. 'BOS I am Sam EOS', 'BOS Sam I am EOS', etc.)

I've tried using map : mini_corpv2 = list(map(lambda x: 'BOS{}EOS'.format(x), mini_corpus)) but it throws 'list' object is not callable

Can anyone tell me what I'm doing wrong or suggest another method to implement this?


Solution

  • I suppose the problem is somewhere else. Your code runs without problems, resulting in

    ['BOSI am SamEOS',
     'BOSSam I amEOS',
     'BOSI am SamEOS',
     'BOSI do not like green eggs and SamEOS']
    

    (so you will probably want to add spaces after BOS and before EOS).

    An alternative solution using list comprehension:

    mini_corpv2 = [f'BOS {x} EOS' for x in mini_corpus]