Search code examples
pythonlistindices

How to get list indices after a specific index


If I have the list: ['a', 'b', 'c', 'd', 'e'], and I want a variable like this: afterC = ['d','e'] - Aka, all items after 'c' get put into their own list. I've tried searching for a solution, but I can't find anything


Solution

  • The list object has an .index() method which returns the index of a given value. This index can be used to slice the list and return the values after the given index.

    For example:

    l = ['a', 'b', 'c', 'd', 'e']
    
    l2 = l[l.index('c') + 1:]
    

    Output:

    >>> l2
    ['d', 'e']
    

    Documentation linked here