Is it possible to declare a variable that contains an if statement? The following pseudocode (written only with the idea of illustrating the example), represents the idea that is pursued, that is, that the variable m takes a different value depending on the value of j.
j = [1, 2, 3]
m = if j[0]:
[{'b': 0.0, 'x': 0.0, 'm': 0.02} for _ in range(100)]
if j[1]:
[{'b': 0.5, 'x': 0.5, 'm': 0.02} for _ in range(100)]
if j[2]:
[{'b': 1.0, 'x': 1.0, 'm': 0.02} for _ in range(100)]
I understand that what you are looking for is a quick assignment of a variable according to a certain condition. There are a few ways to do it (I modified the values in your example a bit because you were always returning the same list):
Using a function
It is a good alternative since it allows better verification of the condition
j
, for example returning a default value if no expected value was chosen.By using dictionaries
It is a direct assignment from a dictionary that has the valid options as its key, a will be emitted
KeyError
if you use any value ofj
not contemplated, unless you access the dictionary using the methodget()
:Literally as you are asking it is not possible. Still, there are a couple of ways to do something very similar in Python. The first is with the so-called Coalescence Operators, and they are used in the following way:
This is evaluated as follows. If the first term/variable is true, then the variable is assigned that first term/variable. If the first term/variable is false, then the variable is assigned the second term/variable. Note that only the first term/variable is evaluated.
The second is with the ternary operator, which is quite similar. You would have to use it as follows:
In this way, the default value is the list that you are indicating when the condition is met and when the condition is not met, then the variable takes the value
None
.As I was saying, it's not exactly doing an if within the assignment, but rather evaluating to assign. This is an unusual way of doing it, but it's the closest thing to your question. I guess you could somehow nest the operations in one of these two ways. Since you are probably investigating the means to reach a final goal, I recommend you do it by functions as Patricio's answer indicates.
You can see more information about these operators in the official documentation of your version of Python. and also in this question of the site in English .