pythonlist

How to split single element of list and maintain order in list?


I have a list:

ll=['the big grey fox','want to chase a squirell', 'because they are friends']

I want to split the 2nd element, ll[1], into "want to chase" and " a squirell".

I want to end up with:

['the big grey fox','want to chase', ' a squirell', 'because they are friends']

Note that the first element needs to be always split so that the last 10 characters are a new element of the list, immediately after the first n-10 char of the element before, so that the order of joined text is not altered.

I currently use:

ll[:1],ll[1][:len(ll[1])-10], ll[1][-10:],ll[2:]

but is there a prettier way of doing this?


Solution

  • You can use:

    ll[1:2] = ll[1][:-10], ll[1][-10:] 
    

    to replace a second element with a split pair.

    Sidenote: if you want the exact output as in your question, you need to split on index -11.

    Sidenote2: ll[1][:len(ll[1])-10] is equivalent to ll[1][:-10]