+ 1

How to create a dynamic veriable in in a loop for example increment a1 to a100 in a python loop?

How to create a dynamic veriable in in a loop for example increment a1 to a100 in a python loop?

7th May 2019, 8:00 PM
Karzan
4 Respuestas
0
Hello karzan If you are looking to make something like: for i in range(1,101): a_i = ... # some (calculated) value Then I would have to inform you that Python doesn't support such a thing. There are 2 other ways that you could follow to get the same effect though: 1. Use a list. A list represents an ordered sequence of objects, with indices. So you would store all the values that you wanted to store in the variables a1-a100 in a list like this: a = ['value1', 'value2', ..., 'value100'] and you can call these values with their respective indices: a[0], a[1], ..., a[99]. 2. Use a dictionary. A dictionary is an unordered data structure with key:value pairs. You can create the dictionary in a dynamic way: a = {} # first create an empty dictionary i = 0 # create an iterator and set its initial value to 0 (or any other number of your preference) while i <= 100: key = ... # create a variable called 'key' and calculate its value. This variable will be used as our key in the dictionary value = ... # idem dito for our value a[key] = value # store the key:value pair in the dictionary i += 1 Hope this has benefited you. Let me know if something needs to be explained further.
7th May 2019, 8:38 PM
Hiro
Hiro - avatar
0
Thanks Hiro. The first option will not work for me because it will take so long to type and I have a very long code. The second option is possible but it's not clear can you share an example?
7th May 2019, 11:01 PM
Karzan
0
Hello karzan You could do the first method a lot faster with list comprehension. I have illustrated both methods in the code below: https://code.sololearn.com/ci4VEGcK7l9k/?ref=app Hope this gives you an idea. If it still doesn't help, can you let me know what the values are that you want to store in variables? Maybe I can be more of a help if I have that info.
7th May 2019, 11:37 PM
Hiro
Hiro - avatar