Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading