Python Forum
Best way to accommodate unknown number of variables? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Best way to accommodate unknown number of variables? (/thread-37266.html)



Best way to accommodate unknown number of variables? - Mark17 - May-20-2022

Hi all,

I've run up against this issue a number of times so I thought I'd seek advice on the best way to handle it.

Suppose I have a large data file and I don't know how often a pattern will repeat. Each time it occurs, though, I need to capture details and later evaluate to select which one I'll need.

What is the best way to name variables in this case?

One approach would be to define as many or more sets than I'll ever need. For example:
dte0 = dte1 = dte2 = dte3 = ... = dte50 = 0
row_num1 = row_num2 = row_num3 = ... = row_num50 = 0
That seems like a pain.

I'd rather define and initialize the variables with a loop like:
variable_set = ['dte'+ str(i) for i in range(50)]
print(variable_set)
Now I've got the variable names in a list... could I then initialize them as a loop?

This doesn't work:
for i in len(variable_set):
    int(variable_set[i]) = 0
    
print(variable_set)
Even if that did work, I think I might have just changed the list to all zeros, which loses the variable names for later use in the program. I don't know how to keep the strings as variable names for later use...

Any general thoughts for something like this?


RE: Best way to accommodate unknown number of variables? - ndc85430 - May-20-2022

No no no! Just use a collection for your values (list, dict, set, tuple as appropriate) instead of trying to dynamically generate variables.


RE: Best way to accommodate unknown number of variables? - Gribouillis - May-20-2022

The solution is to never use numbered variable names like this. Instead use containers like lists or dicts

>>> dte = [0] * 50
>>> dte[7]
0
>>> dte[8] = 43
>>> dte[5:10]
[0, 0, 0, 43, 0]



RE: Best way to accommodate unknown number of variables? - bowlofred - May-20-2022

Usually you wouldn't bother to pre-initialize, especially if you didn't know the exact number beforehand. Instead, just process as necessary and append or add to a collection.

results = []
with open("mydata") as f:
    for line in f:
        # process each line as necessary.
        hostname = line.split()[0]
        results.append[hostname]

# all the processed hostnames are now in the results list
...



RE: Best way to accommodate unknown number of variables? - snippsat - May-20-2022

Here a kind of hidden👻 secrets.
>>> dte1 = 1
>>> dte2 = 2
>>> dte3 = 3
When make 3 variables like this Python store them in a internal dictionary called globals()
Can test this with:
>>> globals()['dte3']
3
>>> globals().get('dte1')
1
So as mention use a data structure like eg dictionary and do not make 50 variables.
>>> d = {f'dte{i}':i for i in range(0,10)}
>>> d
{'dte0': 0,
 'dte1': 1,
 'dte2': 2,
 'dte3': 3,
 'dte4': 4,
 'dte5': 5,
 'dte6': 6,
 'dte7': 7,
 'dte8': 8,
 'dte9': 9}

# Same result but now have made a own visible dictionary
>>> d['dte3']
3
>>> d.get('dte1')
1



RE: Best way to accommodate unknown number of variables? - Mark17 - May-20-2022

Thanks everyone! You've given me several good ideas here.


RE: Best way to accommodate unknown number of variables? - Skaperen - May-21-2022

instead of a bunch of different variable names, i'd make a (big) list:
mylist = howmany*[initialvalues]
then i can access each one by its index. if i need to access some specific one in the code i can just hard code the index like mylist[0] first the first one.


RE: Best way to accommodate unknown number of variables? - Pedroski55 - May-22-2022

Well, maybe dynamically generated variables is something for a future version of Python, because, in PHP, that is a) possible and b) very handy!

This dynamically generates data arrays for output in html tables.

The number of questions varies from time to time. Like the OP said, I don't know or care how many questions there are each time.

But, of course, the whole output.html.php file is generated using Python and couple of text files!

Quote:if(isset($_POST['studentnum'])) {
$count = count($questions);
for($i=1; $i<=$count; $i++) {
//echo '$i is ' . $i . '<br>';
$Qnr = 'Q' . $i;
//echo '$Qnr = ' . $Qnr . '<br>';
${'Q'.$i} = $questions[$i-1];
// should be an array of 3 arrays, 3 results, 1 for each gender
${"men$i"} = displayAllQs($Qnr);
//echo 'This is ${"men$i"} <br>';
//$name = 'men' . $i;
//echo 'results array is ' . $name . '<br>';
//print_r(${"men$i"});
//echo '<br>';
${"menP$i"} = displayAllQs($Qnr);
$lenmenP = count(${"menP$i"});



RE: Best way to accommodate unknown number of variables? - ndc85430 - May-23-2022

No. As above the correct solution is to use containers (at least in Python) because those are dynamic in size. Resorting to dynamically generated variables just gives you code that's hard to understand and maintain.


RE: Best way to accommodate unknown number of variables? - Skaperen - May-30-2022

dynamic variable names in general practice (specific cases can be shown to be OK) should not be done because risks like name collision and security. that PHP (and others) allow this does not reduce these risks. Python provides one or more isolated name spaces for this called dictionaries. if all indexes are integers, lists can be used. but a dictionary helps keep your project simple and any hashable type can be used. even a tuple containing only hashable data can be used as a "name" (actually a key).