-1

I have a list of variables in Python:

a = 1  
b = 0  
c = 0

These come from part of a script that gets user input for certain fields to process, so 1 means "do something to 'a'" and 0 means "do not include." So it would be useful to know which fields need to be used later in the script, i.e. which of them equal 1.

What's the best way to find which of a, b or c is equal to 1?

I tried this method (from here):

test_list = [a,b,c]  
next((x for x in test_list if x == 1), None)

Which returns 1, but I'm looking for it to return a. This is precondition, the next step in the script takes the variables that equal 1 and does something with them, by variable name rather than value.

I could do it long-hand like this:

if a == 1:
    print "a"
if b == 1:
...

but I suspect there's a nice Pythonic way to find the name of a variable from a list of variables that equals a specific value.

Community
  • 1
  • 1
Evan
  • 1,960
  • 4
  • 26
  • 54
  • Why not, instead of having a ton of variables with different values, just put those values in a list? – nbryans Feb 06 '17 at 22:28
  • Your question doesn't really make sense; variables don't have names. See http://nedbatchelder.com/text/names.html – jonrsharpe Feb 06 '17 at 22:29
  • Don't do things this way. Use a container, like a list, or a dictionary. – juanpa.arrivillaga Feb 06 '17 at 22:30
  • Seems like an X-Y problem. What are you trying to accomplish that leads you to want to do such an odd thing? – Fred Larson Feb 06 '17 at 22:32
  • @FredLarson I would bet a homework assignment... – GantTheWanderer Feb 06 '17 at 22:47
  • I appreciate the pointers. It's frustrating when asking a question for someone to say "don't do that," or "that's weird." I thought by asking a question it was clear that I didn't understand something. Also, not homework -- how is that relevant? – Evan Feb 06 '17 at 23:00

1 Answers1

2

You should consider using a dictionary (a mapping) instead of a list, as names only reference objects but are not the objects themselves:

d = dict(a = 1, b = 2, c = 0)
print(next((k for k, v in d.items() if v == 1), None))
# a
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139