Home > OS >  In Python how do I slice a list based on an item in the list?
In Python how do I slice a list based on an item in the list?

Time:04-15

list1 = ['5', '3', '2', '1']
j = '3'

How do I extract from that list from j to the end of the list? In this example giving me:

['3', '2', '1']

when I know j, j is always in the list and the list is always filled with unique values?

CodePudding user response:

As comments suggest you can get the index number of an item in a list by using index method. Just like this:

>>> list1 = ['5', '3', '2', '1']
>>> list1.index('5')
0
>>> list1.index('1')
3

And then use it to reach the item you want:

>>> i  = list1.index('2')
>>> list1[i]
'2'

CodePudding user response:

so since you know the value of j here, we can get the index of j in the list using list1.index(j) now we have to get all the items after j, so we can use this: list1[list1.index(j):]

what this basically does is, it gives all the values from the specified index (our case j) till the end of the list this should give you the desired output!

  • Related