Search code examples
pythonpython-3.xfor-looplist-comprehensionone-liner

List Comprehension Hackerrank - can you tell me if this one liner is permittable to use?


I was currently trying to solve this challenge - List Comprehensions - and came up with this solution in python3:

if __name__ == '__main__':
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())

list = []
for a in range(0, x+1):
    for b in range(0, y+1):
        for c in range(0, z+1):
            if a + b + c != n:
                list.append([a, b, c])
print(list)

But what's Bothering me is this one liner solution that I found in discussion:

x, y, z, n = (int(input()) for _ in range(4))
print ([[a,b,c] for a in range(x+1) for b in range(y+1) for c in range(z+1) if a + b + c != n ])

I'm a complete beginner and don't know if this one liner is permittable to use and if permittable, can you please explain how this one liner works? Can you share any source from where I can start learning how to use such one liner codes?


Solution

  • list is a built-in data-type in python, so you should not use list as an identifier (variable name).

    and your code itself is the explanation of the one-liner.

    The trick is, you start with the expression you want to execute, and after that you write the outer-most for-loop, going to the inner loops and lastly, add the condition you wanna check. Also, remember to embrace the whole thing with the proper data-structure notation.

    for example: if I want to list all the even numbers upto 100 which are divisible by 3, i will do:

    numbers = [i for i in range(0, 100, 2) if i % 3 == 0]
    print(numbers)
    

    output:

    [0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96]