-1

I want to know if there is anyway to evaluate a list of conditions every time the list is printed.

For ex:

a,b,c,d=10,15,30,56
li=[a%10==0, b<5, c//3==10, d%2==0]
print(li)
b=3
print(li)

The first and second print functions are giving [True, False, True, True]

How can I make the list update its values according the conditions mentioned in it above.

So that the second print function prints [True, True, True, True] according to the updated value of variable b.

  • 2
    Use a function to update – Sheldore Nov 03 '18 at 16:26
  • @PatrickArtner, that would work without paranthesis as well. – Austin Nov 03 '18 at 16:30
  • @Austin it would? nice to know - and it is cheaper, no tuple construction – Patrick Artner Nov 03 '18 at 16:34
  • @Tyrion: [why is using eval a bad practice](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) – Patrick Artner Nov 03 '18 at 16:37
  • 1
    @PatrickArtner, there still is tuple construction. the interpreter will interpret the comma separated list of values as a tuple and then unpack it to the variables. – sam-pyt Nov 03 '18 at 16:40
  • 1
    @PatrickArtner Same tuple construction. Tuples are defined by the comma-separated sequence. Except for empty tuples, parentheses are optional unless required in the particular context. They are not needed here because assignment '=' binds even more loosely than commas. `a, b = 1, 2` makes no sense if parsed as `a, (b = 1), 2`. – Terry Jan Reedy Nov 03 '18 at 16:40
  • @TerryJanReedy darn - thx for explanation – Patrick Artner Nov 03 '18 at 16:43

2 Answers2

1

Its possible, its called a function:

a, b, c, d = 10, 15, 30, 56

def get_list(a,b,c,d):
    return [a%10 == 0 , b < 5, c//3 == 10, d%2 == 0]

print(get_list(a,b,c,d))

b=3
print(get_list(a,b,c,d))

Output:

[True, False, True, True]
[True, True, True, True]

python lambda would be possible as well - they are lazy bound when executed - hence reflect the changes to b:

k = lambda: [a%10 == 0 , b < 5, c//3 == 10, d%2 == 0]

print(k())   # execute the lambda
b=3
print(k())   # execute again

Output:

[True, False, True, True]
[True, True, True, True]
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

Probably the best way would be to use a function:

def evaluate(a, b, c, d):
    return [a%10==0, b<5, c//3==10, d%2==0]

print(evaluate(a, b, c, d))
Dirkx Senne
  • 95
  • 1
  • 3
  • 14