Search code examples
pythonlist-comprehension

Is there any way to write this code with List comprehension in python?


What should be the correct way of writing this List Comprehension for calculating the value for result?

    nothing = [0,0,0,0,0,0]
    box = [1,2]
    boxes = [box,box,box]
    page = [boxes,boxes]
    pages = [page, page]
    npr = [nothing, pages]

**result =  [box for box in npr.pages[i].boxes] where i is the counter variable**

P.S. This is pseudocode.


Solution

  • Like this:

    result = [i for boxes in npr[1] for i in boxes]
    print(result)
    

    Output:

    [1, 2, 3, 4, 5, 6]
    

    In this case why not just use:

    result = npr[1][0]
    

    Or:

    result = sum(npr[1], [])