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
Chathuri fernando
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
reticentroot
source
to share
You can use index
:
l[l.index('but')+1:]
>>> ['nothing', 'to', 'do']
+3
MMF
source
to share
Join the list, split it and re-split it.
' '.join(l).partition('but')[-1].split() # ['nothing', 'to', 'do']
+2
Jared goguen
source
to share