For loop with list? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
0

For loop with list?

I have list = ['black', 'red', 'blue', 'green']. How to do proper loop if I want to create 4 variables with names taken from that list?

12th Apr 2020, 5:58 PM
Paw
Paw - avatar
14 ответов
+ 4
You should do a try by yourself first. If you still encounter problems, then put your code in playground and link it here. Thanks!
12th Apr 2020, 6:51 PM
Lothar
Lothar - avatar
+ 3
Why do you need it with for loop? I'm asking because what you want to do sounds unreasonable to me, and I'm wondering if there's a more natural way. Can you tell us more about what exactly you're trying to do?
12th Apr 2020, 9:48 PM
HonFu
HonFu - avatar
+ 2
Here's without a for loop. a, b, c, d = ['black', 'red', 'blue', 'green'] print(a, b, c, d)
12th Apr 2020, 6:18 PM
rodwynnejones
rodwynnejones - avatar
+ 2
Yeah, it can be done with exec, but whenever you want to use exec, it's already an indicator that your idea might be what I called 'unreasonable'. You can always sort out problems like this without the exec bomb.
13th Apr 2020, 9:02 AM
HonFu
HonFu - avatar
+ 2
I can do it without a for loop it will be easy
14th Apr 2020, 6:28 AM
Vijay(v-star🌟)
Vijay(v-star🌟) - avatar
+ 1
You could use a second list (instead of variables) and store the result of each calculation there.
13th Apr 2020, 6:59 AM
HonFu
HonFu - avatar
13th Apr 2020, 10:30 AM
rodwynnejones
rodwynnejones - avatar
0
I need a version with for loop.
12th Apr 2020, 6:25 PM
Paw
Paw - avatar
0
Buttons add elements to list when are pressed. Next period of the app is definition which create variable for each element in list and do calculations dependent from each name.
13th Apr 2020, 6:38 AM
Paw
Paw - avatar
0
I have seen s similar request on here, it was done with a format string and the eval or exec function. If i track it down, ill post the link.
13th Apr 2020, 8:46 AM
rodwynnejones
rodwynnejones - avatar
0
I think that the best solution for your problem is using a dictionary. From there you might be able to objectify it. Maybe redefining the __dict__ attribute of your custom class.
13th Apr 2020, 2:11 PM
GeraltdeRivia
0
A bit late, but i want to share it anyway: lst = ['black', 'red', 'blue', 'green'] for ind, i in enumerate(lst,1): locals()[i] = ind # i can not remember where i saw this: locals()[...] ??? # print all generated variables: for j in lst: print(f'{j:6} - {eval(j)}') # or with zip and 2 iterables: for num, i in zip(range(1,),lst): locals()[i] = num for j in lst: print(f'{j:6} - {eval(j)}')
14th Apr 2020, 4:28 PM
Lothar
Lothar - avatar
16th Apr 2020, 7:58 AM
Paw
Paw - avatar
- 1
list = ['black' , 'red', 'blue', 'green'] for x in list: print(x)
6th Jul 2020, 5:07 AM
JR.