1

I have two questions about the Python list.

  • Is there a way to insert items in the beginning and end of the python list? For instance, suppose that I have the list below
A = ["I","am","happy"]

What is the easiest way to generate the list B below from the list A, by specifying that I want the additional items to be at the beginning and at the end of the original list?

B = ["<bos>", "I", "am", "happy", "<eos>"]
  • suppose now that I want to add a special token <spec_token> right before the token am. Is there a way to do so by specifying before which token (am in this case) I want to insert the <spec_token> at? So continuing from the previous example, I want to generate the list C below:
C = ["<bos>", "I", "<spec_token>", "am", "happy", "<eos>"]

Thank you,

PS: Please note that I do not want to use the token index as my parameter to insert a different token into the list. I want to use the specific tokens themselves as my parameter to update the list.

chico0913
  • 577
  • 4
  • 10
  • 22
  • 1
    Possible duplicate of [Insert an element at specific index in a list and return updated list](https://stackoverflow.com/questions/14895599/insert-an-element-at-specific-index-in-a-list-and-return-updated-list) – Nicolas Gervais Nov 24 '19 at 00:38
  • Please note that I don't want to use the index as the parameter to insert token. I want the specific token to be my parameter – chico0913 Nov 24 '19 at 00:39
  • _I do not want to use the token index as my parameter to insert a different token into the list._ Why is that? – AMC Nov 24 '19 at 02:00

2 Answers2

3

Try this, it should help you with any insert your looking to do:

 B.insert(B.index("am"), '<spec_token>')     

# ['<bos>', 'I', '<spec_token>', 'am', 'happy', '<eos>']

oppressionslayer
  • 6,942
  • 2
  • 7
  • 24
1

That would be using A.insert(index, value) So in your case, the statement would be

A.insert(0, '<bos>')

MoonMist
  • 1,232
  • 6
  • 22