Search code examples
pythonpython-3.xcoding-style

Please explain the following inline python code? index = [n for n, value in enumerate(self.Variable[i]) if value == 1]


I need to understand the following code. The code is from a class method. Code snippet

index = [n for n, value in enumerate(self.Variable[i]) if value == 1]


Solution

  • The above code can be rewritten as:

    indices = []
    for n, value in enumerate(self.BUSES[i]):
        if value==1:
            indices.append(n)
    

    enumerate returns a pair of (index, value at that index) for a given list. So you are testing if value at a given index is 1, and if that is true, you add the index to indices.