Python Forum

Full Version: Best way to accommodate unknown number of variables?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
No no no! Just use a collection for your values (list, dict, set, tuple as appropriate) instead of trying to dynamically generate variables.
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]
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
...
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
Thanks everyone! You've given me several good ideas here.
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.
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"});
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.
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).