1

This maybe a stupid question but I'm having trouble finding the answer.

I'm using Flask/Python and have a .py file named 'hero.py' that contains a dict ex.

heroes = {'ironman': 'Strength, Covert', 'IronFist': 'Tech, Strenght'}

def hero():
    hero, attribute = random.choice(list(heroes.items()))
    if 'Tech' not in attribute:
        hero, attribute = random.choice(list(heroes.items()))
    if 'Tech' in attribute:
        return(hero, attribute)

What I'm wondering is how to use just the attribute variable when I call the function?

I can do something like:

my_hero = hero()
print(my_hero)

But how do I print out only the attribute of that hero? Hopefully that makes sense?

1
  • Keep in mind that random.choice might find an unsuitable entry both times. What would happen then? Did you perhaps want to use a loop instead? Better yet, try to find all the entries that do qualify, and make a random.choice from only those. Commented Jun 5, 2022 at 16:34

2 Answers 2

5

When you have a function that returns indexable data such as a tuple or list, you can assign the set of contained values to a variable in multiple ways:

def my_function():
    return ('a', 'b')

You can assign the return value to a single variable:

example_1 = my_function()

>>> example_1
('a', 'b')

Or you can assign it to multiple variables, matching the number of values in the object:

example_2a, example_2b = my_function()

>>> example_2a
'a'

>>> example_2b
'b'

If you only need one of the values but not the other, a common form is to assign the unneeded value to _, which is considered a standard throwaway:

_, example_3 = my_function()

This works even if you have a ton of values and want to throw away more than one:

def my_next_function():
    return ('a', 'b', 'c', 'd', 'e')

_, example_4, _, _, _ = my_next_function()

>>> example_4
'b'

Of course, you could also simply do positional assignment, e.g.:

example_5 = my_function()[1]

However I prefer the _ method as I think it makes the intention cleaner - that is, it tells the reader explicitly that you only care about one value and not the others. But to each their own

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This works perfect and thank you even more for the detailed explanation. Makes much more sense now, especially the _ bit, that clears up a different question I was having. Two birds with one stone!
1

print(hero()[0]) should work for first attribute

1 Comment

Thank you! That works great, I didn't know you do that actually. Was having trouble finding an example too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.