-2

I have 5 variables and they take either a 1 or 0. I am trying to find which among those 5 variables are set to 1.

For example:

var_1 = 1 
var_2 = 1
var_3 = 0
var_4 = 1
var_5 = 0

I am expecting to get var_1, var_2 and var_4 as they are equal to 1.

scott martin
  • 1,253
  • 1
  • 14
  • 36

1 Answers1

1

Try this:

for i in range(1,6):
    exec(f"if var_{i} == 1: print('var_{i}')")

This prints:

var_1
var_2
var_4

Or as chester suggested, use:

[i for i,v in globals().items() if v==1]

or the locals() (may raise Runtime error if you loop through it):

[i for i,v in locals().items() if v == 1]
Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34
  • 1
    You can use [`globals()`](https://docs.python.org/3.3/library/functions.html#globals) to get global variables names try this `[i for i,v in globals().items() if v==1]`---->output is `['var_1', 'var_2', 'var_4']`. for local variables use [`locals()`](https://docs.python.org/3.3/library/functions.html#locals) – Ch3steR Apr 13 '20 at 05:35
  • @JoshuaVarghese I have added link to the documentation of `globals()` and `locals()` in the previous comment. – Ch3steR Apr 13 '20 at 05:43
  • @Ch3steR is usage of exec() recommended to be avoided? – Joshua Varghese Apr 13 '20 at 05:44
  • @JoshuaVarghese Most programmers try to not use `exec` and `eval`. It's there last resort. Take a look at this [answer](https://stackoverflow.com/questions/9672791/how-to-safely-use-exec-in-python) – Ch3steR Apr 13 '20 at 05:47
  • @JoshuaVarghese This [answer](https://softwareengineering.stackexchange.com/a/191628) provided by Martijn Pieters explains well – Ch3steR Apr 13 '20 at 05:50
  • 1
    @JoshuaVarghese TBH I wouldn't use `globals()` or `locals()`. It's better to use a suitable data structure here something like a list or a dictionary ;) – Ch3steR Apr 13 '20 at 06:17