0

I know this can probably be done in one line and it's pretty simple but I keep failing on syntax. I want to do the following:

for tag in TAGS.values():
    if tag in myset:
       found_tag = tag
       break

I have tried things like

found_tag = tag if tag in myset for tag in TAGS.values()

But I keep getting syntax errors on the for. Is there a one line way to do this in python?

2
  • do you want the for loop stop (break) once it found the first tag in myset? Commented Sep 16, 2014 at 20:28
  • @Vor yes that would be great because I know there will only be one solution, there should have been a break in that loop, will edit to accurately reflect Commented Sep 16, 2014 at 20:43

2 Answers 2

4

If you want to get the first satisfactory tag and then stop, use next.

found_tag = next((tag for tag in TAGS.values() if tag in myset), None)

This will give None if no such tag is found.

If you want to get all matching tags, you can do this:

found_tags = [tag for tag in TAGS.values() if tag in myset]
Sign up to request clarification or add additional context in comments.

Comments

1

You are missing the squared brackets, and the if is better placed at the end. Try:

found_tag = [tag for tag in TAGS.values() if tag in myset]

One other way to deal with this is to use set operations (need to use the set() constructor only if the variables are not already sets):

found_tag = (set(TAGS.values()) & set(myset))

You can use .pop() to get the only item if there is only one:

found_tag = (set(TAGS.values()) & set(myset)).pop()

1 Comment

I was wondering moreso if there was a way to not have it in a list. Obviously I can just index out of this list, but I know that the above code will only have one answer so there is no need to have it in list. Guess I'll have to live with this. Thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.