How do I create a variable where one index depends on the value of another index?
Peter Otten
__peter__ at web.de
Tue Aug 7 14:49:39 EDT 2018
giannis.dafnomilis at gmail.com wrote:
> Hey Peter.
>
> This worked like a charm! I can't believe I did not think of that, after
> wasting so many hours on it.
>
> Thank you so much for the help!
You can make these things easier to debug by breaking your code into small
functions. If there were separate functions
def make_finalcosts(...):
... # i is a local variable here
def make_probvars(...):
... # i is not defined here and there's no global i
you'd have seen a NameError exception similar to the one below:
>>> def example(m, n):
... return [i + k for j in range(m) for k in range(n)]
...
>>> example(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in example
File "<stdin>", line 2, in <listcomp>
NameError: name 'i' is not defined
Writing a function in such a way that the result only depends on the
function's arguments allows for easy testing.
More information about the Python-list
mailing list