Split a list from some element and get the values ​​of elements in another list in Python 2.7

This is my list:

l = ['today','is','a','holiday','but','nothing','to','do']

      

I want to put items after "but" in another list, for example:

another_list = ['nothing','to','do']

      

I've tried like this:

l = ['today','is','a','holiday','but','nothing','to','do']
for element in l:
   parts = element.split('but')

      

But it does not provide the expected result.

+3


source to share


3 answers


You are splitting an element of an array, not a string .. so in that case you won't work. There is nothing to divide. Find the index instead and continue from there. Checkout https://www.tutorialspoint.com/python/python_lists.htm to learn more about python list



l = ['today','is','a','holiday','but','nothing','to','do']
# get the index of but
i = l.index("but") # "This method returns index of the found object otherwise raise an exception indicating that value does not find."
# print everything after "but" using slice logic.
print l[i+1:]

      

+3


source


You can use index

:



l[l.index('but')+1:]
>>> ['nothing', 'to', 'do']

      

+3


source


Join the list, split it and re-split it.

' '.join(l).partition('but')[-1].split() # ['nothing', 'to', 'do']

      

+2


source







All Articles