-1

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.