Search code examples
pythonlist-comprehension

2 List Comprehension in python


I tried to write this, where s is just an int

 for box in current_boxes:
        for i in range(len(box)):
            box[i] = box[i]*s
        all_boxes.append(box)

as a list comprehension. But my result is not the same. That's what I've tried.

all_boxes = [all_boxes.append(box[i]*s) for box in current_boxes for i in range(len(box))]

Any help is much appreciated.


Solution

  • When using list comprehension you're building a new list. You don't need to use append.

    You don't need to use an interator with list indices and range either.

    The inner loop would look like this :

    [value*s for value in box]
    

    Here we're building a new list which be the original list with each item multiplied by your s variable.

    Now, we need to create a such list for each box in your current_boxes.

    The outer loop that would do this may be like :

    [box for box in current_boxes]
    

    When combined :

    all_boxes = [[value*s for value in box] for box in current_boxes]