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?
14 Answers
+ 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!
+ 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?
+ 2
Here's without a for loop.
a, b, c, d = ['black', 'red', 'blue', 'green']
print(a, b, c, d)
+ 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.
+ 2
I can do it without a for loop it will be easy
+ 1
You could use a second list (instead of variables) and store the result of each calculation there.
+ 1
Have a look at some of the reply in here.
https://www.sololearn.com/Discuss/2115531/can-i-affect-all-items-of-a-list-into-multiples-variables
0
I need a version with for loop.
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.
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.
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.
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)}')
0
I changed the concept.
https://code.sololearn.com/cnG9cjyCuFM3/?ref=app
- 1
list = ['black' , 'red', 'blue', 'green']
for x in list:
print(x)