Reputation: 369
I got a quick question about my program. I want to assign 0 to all the variables named rdf12(i)
, like rdf12(1) = 0 rdf12(2) = 0
. Here is my code:
for i in range(200):
rdf12(i) = 0
But it turned out not that easy and I had an error said:
SyntaxError: can't assign to function call
So how can I edit my code to fix it?
Upvotes: -1
Views: 73
Reputation: 318468
The item access operator in Python is []
, not ()
.
So you probably want rdf12[i] = 0
instead. However, this only works if you have a list named rdf12
that already contains 200+ elements. Not if you have/want actual variables named rdf120
, rdf121
, ... - if that't the case you need to refactor your code (while it would still be possible, I'm not going to post that solution here since it would be incredibly ugly). Anyway, this is what you should use:
rdf12 = [0 for i in range(200)]
That gives you a list containing 200 zeroes. You can then access the elements using rdf12[0]
, rdf12[1]
, ..., rdf12[199]
and assign other values to them etc.
Upvotes: 1
Reputation: 19524
You can't have brackets (
and )
as part of the variable name as this syntax is used to call a function. You are effectively trying to call a function rdf12
with the values of i
.
If you name your variables rdf12_0
, rdf12_1
, etc you may be able to access them through the locals()
function which returns a dict of local variable declarations, however I believe making modifications to this dict is not guaranteed to work and as such is a really bad idea.
>>> rdf12_0 = 0
>>> lcls = locals()
>>> print(lcls['rdf12_0'])
0
>>> name = 'rdf12_' + str(0)
>>> lcls[name] = 34
>>> rdf12_0
34
I would suggest instead, storing your values in a list
:
>>> rdf12 = [34, 12, 9, 97]
>>> rdf12[0]
34
>>> rdf12[1]
12
>>> for i in rdf12:
... print(i)
...
34
12
9
97
Upvotes: 0