I have a symbolic sequence like x1,x2,...,x20 (without brackets). Can I take this sequence as variables in python? in other word y=x1,x2,x3,...,x20
?
At fist my list was x=[x1,x2,...,x20]
and with command *x
I converted it to sequencex1,x2,...,x20
and now for continuing my program I need to take this sequence as variable.

- 4,165
- 1
- 8
- 31

- 19
- 5
-
1Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – Mechanic Pig Aug 14 '23 at 10:26
-
Please add more information about what you're trying to do. *x on an array doesn't make any sense in Python – Timothee W Aug 14 '23 at 10:34
-
1make it clearer that you are working with `sympy`. But also don't confuse the symbols and python variables that can reference them. Study the sympy examples with care – hpaulj Aug 14 '23 at 10:36
-
Please make it clear, what x1, x2, ... are. Do you have strings? Are these variables? If yes, how are they defined? – Matthias Aug 14 '23 at 10:41
-
I want to take a variable like y that equal to symbolic sequence x1,x2,...,x20 – hojat saeidi Aug 14 '23 at 10:42
-
I have not string @Matthias, x1,x2,... are symbolic variables – hojat saeidi Aug 14 '23 at 10:43
-
what are you going to do with that sequence? – Ahmed AEK Aug 14 '23 at 11:04
-
I need them for optimization – hojat saeidi Aug 14 '23 at 11:28
-
be more specific about the 'optimization'. What `sympy` code? – hpaulj Aug 14 '23 at 14:26
2 Answers
Since you say that you used *x
to convert the sequence to variables (and you can only do *x
in a function call or function signature like:
def f(x1,x2):
print(x1, x2)
x = var('x1 x2')
>>> f(*x)
(x1, x2)
it seems like you mean that "once in the function, can I get the list of variables again?" The answer is "yes" -- the same way that you made them in the first place:
def f(x1, x2):
y = x1, x2
print(y)
>>> f(*x)
(x1, x2)
But maybe you mean "without having to retype the list?" The solution is to pass them as a tuple instead of unpacking them with the "*" operator:
def f(y):
print(y)
>>> f(x) # passing as tuple, not unpacking
(x1, x2)
(It is always better to add a little code so there is less guessing what you mean.)
Yes, you can indeed treat a sequence of symbols as separate variables in Python. Your initial approach of having a list x = [x1, x2, ..., x20] and then unpacking it using the * operator is correct to create a sequence. Suppose your initial list is: x = [value1, value2, ..., value20] You can unpack this list directly into variables using tuple unpacking: x1, x2, x3, ..., x20 = x Now, x1, x2, x3, ..., x20 are independent variables with the corresponding values from the original list. If you want to continue working with these variables as a sequence, you can simply reference them in a tuple or list again: y = x1, x2, x3, ..., x20 # This creates a tuple