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

Question:

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:

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.

Asked By: Jugilismaani

||

Answers:

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)
Answered By: Bhargav

I didn’t understand if you want to include images or image names, I believe this solution can help you in any of the cases:

list = []

for i in range (20):
  list.append(image+"{}".format(i))

print(list)
Answered By: Pedro Freitas Lopes

I found a solution on how to do this this way, even though @Bhargav gave a much more practical solution. Posting this in case it helps someone else in some way. Using eval()

list = []

for i in range (1,20)
  list.append(eval("image" + str(i)))
Answered By: Jugilismaani
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.