Is there a way to simplify this script using in keyword or anything like this:

searched_value = 3
data = [("a", 1), ("b",2), ("c",3)]

### can be simplified ?
test = None
for i in data:
    if i[1] == searched_value:
        test = i[0]

  • \$\begingroup\$ Is this your entire program? If not, you need to show it. \$\endgroup\$ – Reinderien Jul 27 '20 at 14:43

I don't think there is, except maybe unpacking the pairs:

test = None
for k, v in data:
    if v == searched_value:
        test = k

You could use next, but I wouldn't call it simpler:

test = next((k for k, v in data if v == searched_value), None)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.