Defining variables and putting them in al list simultaneously | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Defining variables and putting them in al list simultaneously

For a game I’m creating i have an issue. I have a lot of cards, which amount I might wanna change later. So I have to assign variables: amount_of_card_1 = 5 amount_of_card_2 = 7 amount_of_card_3 = 3 . . amount_of_card_100 = 6 Now I wanna create a list with all the variables I have just defined. Do I have to write them manually in a list? I’m looking for a easier way. Thanks for your help!!!

17th Jan 2019, 7:03 AM
clemens
6 Answers
+ 1
Why does that code not work? i = 5 eval('a' +str(i)) = 7 print(a5)
17th Jan 2019, 3:50 PM
clemens
+ 8
You could use a dict too: amount = {1: 5, 2: 7, 3: 3} etc. and access the values like this: amount[2] # 7 If you already made 100 variables (I hope you didn't) and want to put all of their values in a list, you can do something like: amount_of_card_1 = 5 amount_of_card_2 = 7 amount_of_card_3 = 3 (...) amount = [] for i in range(1, 101): amount.append(eval('amount_of_card_' + str(i))) print(amount) # [5, 7, 3, (...)] If you want the list to contain the variable names instead of their values, remove the eval(). Or do something like this: amount = [l for l in locals() if l.startswith('amount_of_')] print(amount) # ['amount_of_card_1', 'amount_of_card_2', 'amount_of_card_3', (...)]
17th Jan 2019, 7:24 AM
Anna
Anna - avatar
+ 8
Anna you don't need eval() for this because locals() returns a dict for i in range(10): exec('amount_of_' + str(i) + '=' + str(i)) dct = {key: value for key, value in locals().items() if key.startswith('amount_of_')} print(dct) clemens it doesn't work because you're trying to assign 7 to the result of a function. Use exec('a' + str(i) + '= 7')
17th Jan 2019, 4:25 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 5
Don't make separate variables. Put the numbers in a list in the first place. amount_of_cards = [5, 7, 3, 6] Be sure to check out the python lessons about lists, then you should be able to understand it better.
17th Jan 2019, 7:12 AM
Tibor Santa
Tibor Santa - avatar
+ 5
It checks locals() (where all your local variables are stored) for local variables that start with "amount_of_". It should be possible to auto-generate a dictionary like this: amount = {var: eval(var) for var in [l for l in locals() if l.startswith('amount_of_')]} (Unfortunately, I can't test it at the moment, but it should work.)
17th Jan 2019, 3:45 PM
Anna
Anna - avatar
+ 1
Thanks for your help! Since its crucial for me to identify and change later easily the amount of each card a simple list is not very helpful. A dictionary is a much better idea. Since i already defined my variables (shame on me) I’ll try your last solution. It looks up every input and checks whether it starts wirh amount_of?
17th Jan 2019, 3:34 PM
clemens