-1

I'm new to python and I have declared some variables in my code but they are almost similar, I would like to know if it is possible to simplify this with a for loop or the like so as not to have 10 lines of declaration?

Left_10 = PhotoImage(file = 'image_10.jpg')
Left_9 = PhotoImage(file = 'image_9.jpg')
Left_8 = PhotoImage(file = 'image_8.jpg')
Left_7 = PhotoImage(file = 'image_7.jpg')
Left_6 = PhotoImage(file = 'image_6.jpg')
Left_5 = PhotoImage(file = 'image_5.jpg')
Left_4 = PhotoImage(file = 'image_4.jpg')
Left_3 = PhotoImage(file = 'image_3.jpg')
Left_2 = PhotoImage(file = 'image_2.jpg')
Left_1 = PhotoImage(file = 'image_1.jpg')

Thanks for your help

PabloS
  • 27
  • 5
  • don't do that. use proper data structure. Check http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html – buran Jun 08 '21 at 07:24
  • Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – buran Jun 08 '21 at 07:26

2 Answers2

2

Use a dict:

Left = {i: PhotoImage(file = 'image_'+str(i)+'.jpg') for i in range(1,11)}

and access with Left[7]

Julien
  • 13,986
  • 5
  • 29
  • 53
1

This is basically a copy of what @Julien said, but as a list instead of a dict:

Left = [PhotoImage(file=f"image_{i}.jpg") for i in range(1, 11)]

And you can access them by index and sort them (unlike the dict): Left[0] # PhotoImage with file=image_1.jpg...