# Symbolic variables in loops

Hi, I got a list of symbolic variables defined like this: P = list(var('P_%d' % i) for i in range(2*n + 1))

But when I try to manipulate these Variables in a for-loop like: for k in range(2,n + 2,2): print(P_k)

I'll get an error "NameError: name 'P_k' is not defined" I'm guessing there is no k in P_k because its one entity 'P_k' :-D But I hope it's possible to fix this by using "%" like in the definition above. Anyone knows how to?

Thanks

edit retag close merge delete

Sort by » oldest newest most voted

Does P[k] work?

more
for k in range(2,n + 2,2):
print(eval("P_%s"%k))


Ugly, I admit. It's hard to just stick in these things. Niles' solution is better.

Edit: But if you insist (I note you also used print in your original example, so it was hard to anticipate your next issue)...

sage: n = 5
sage: P = list(var('P_%d' % i) for i in range(2*n + 1))
sage: for k in range(2,n + 2,2):
....:     tem = eval('P_%s' %k)
....:     x.subs(x=tem)
....:
P_2
P_4
P_6

more

I'm sorry. I hoped there is a direct way to get the variables and used print as a basic example. But this one is interesting. Unfortunately it substitutes x by P_k and not the other way around

@niles: P[k] works, but I need P_k in my loop. In fact I'm trying to substitute P_k by P[k]

@kcrisman: print(eval...) works fine, but N[k] = N[k].subs(eval('P_%s' %k = P[k])) doesn't (SyntaxError: keyword can't be an expression). But this is what I was aiming at.

One solution would be to redefine N[k] everytime any P_k changes. But that would kill my calculation period for bigger n, so that is my last resort

more

Couldn't you just make, inside your loop, temp = eval('P_%s' %k) and use that in your loop? I'll edit my answer.

I don't understand. Why not just include the line "P_k = P[k]"?

1. P_k = P[k] doesn't work in loops with index k (because even if k = 2, P_k =! P_2) 2. When I got an equation using P_2 it will still have P_2 in it afterwards