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

I have a list of images "Image1, Image2, Image3…". Is it possible to use for loop to add all of them to a list?

So I have 20 images and I want to put them to a list. But I only know how to do it by appending them one by one which wastes a lot of space. I did try for loop, but I do not know how to make it work.

This is what I want to do, but by using a loop:

list = []
list.append(image1)
list.append(image2)
...
list.append(image20)

What I have tried:

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

for i in range 20
  a = str(i)
  list.append(image.join(a))

"image is not defined" is the obvious error I get and I understand what is causing it. The "image" is not defined and I am typing it acting as it should be a variable. Is it somehow possible to change the variable "image" into a string, add str(i) onto it, and then change it back to a variable that includes the number? After which I could input it to the append function.

>Solution :

You can simply do that using glob by filtering image extensions from folder itself.

import glob
img_list = []
for img in glob.glob("Path/to/dir/*.jpg"): #If extension of image is .jpg
    img_list.append(img)
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