Search code examples
pythonpython-3.xiteratorlist-comprehension

How to use next iterator within a list comprehension in python3 to get a list without any leading zeroes


Trying to remove all the leading zeroes from a list of array using next() and enumerate within a list comprehension. Came across the below code which works. Can anyone explain clearly what the code does.

example : result = [0,0,1,2,0,0,3] returns result = [1,2,0,0,3]

Edited* - the code just removes the leading zeroes

result = result[next((i for i, x in enumerate(result) if x != 0), len(result)):] 
print(result)

Solution

  • Trying to remove all the leading zeroes from a list of array using next() and enumerate within a list comprehension.

    Are you obligated to use next(), enumerate() and a list comprehension? An alternate approach:

    from itertools import dropwhile
    from operator import not_ as is_zero
    
    result = dropwhile(is_zero, [0, 0, 1, 2, 0, 0, 3])
    
    print(*result)
    

    OUTPUT

    % python3 test.py
    1 2 0 0 3
    %
    

    We can potentially explain the original code:

    result = [0, 0, 1, 2, 0, 0, 3]
    
    result[next((i for i, x in enumerate(result) if x != 0), len(result)):] 
    

    By breaking it down into pieces and executing them:

    enumerate(result)  # list of indexes and values [(i0, x0), (i1, x1), ...]
    [(0, 0), (1, 0), (2, 1), (3, 2), (4, 0), (5, 0), (6, 3)] 
    
    [i for i, x in enumerate(result)]  # just the indexes
    [i for i, x in [(0, 0), (1, 0), ..., (5, 0), (6, 3)]]  # what effectively happens
    [0, 1, 2, 3, 4, 5, 6]
    
    [i for i, x in enumerate(result) if x != 0]  # just the indexes of non-zero values
    [2, 3, 6]
    
    # not needed with this example input, used to make an all
    # zero list like [0, 0, ..., 0] return the empty list []
    len(result)  
    7
    
    # pull off the first element of list of indexes of non-zero values
    next((i for i, x in enumerate(result) if x != 0), len(result))
    next(iter([2, 3, 6]), 7)  # what effectively happens 
    2
    
    result[next((i for i, x in enumerate(result) if x != 0), len(result)):]  # slice
    result[2:]  # what effectively happens
    [1, 2, 0, 0, 3]