Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Tuples Multiple Return Values

eestsaid
eestsaid
1,311 Points

explination required for teacher's notes supporting multiple return values video

The teacher's notes supporting this video reads:

... "Any method that returns more than one value can be assigned to multiple variables. Stay on the lookout for places where you can avoid index lookups and just provide multiple variables.

If you know you'll get back multiple values and you don't care about one of them, assign it to _. For example:

for index, _ in enumerate(my_list):

The list item won't be available in the loop but you'll still have the step count." ...

What would be an example of instance where you get back mulitple values and you don't care about one of them?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,457 Points

Good question! There is some debate as to how "Pythonic" it is to use an underscore as a throwaway variable. The gettext module provides internationalization (I18N) and localization (L10N) services for your Python modules and applications and is usually aliased as as _().

That said, if not using internationalization or localization, here are two areas where I sometimes use the underscore as a throwaway. It is really an opinion question as to which is more readable.

Avoid using count = 0 and count += 1 to control looping

# instead of using count:
count = 0
while count < 10:
    # do something important 10 times
    count += 1

# since count isn't part of the important thing, try using
for _ in range(10):
    # do something important 10 times

When a function returns a tuple and you only need part of it

import re

string = Step C must be finished before step W can begin."

def decode(line):
    """"parsing lines of the form:
    Step B must be finished before step X can begin.
    """"
    results = re.search(r'^Step\s(\w).*step\s(\w)\scan\sbegin\.$', line)
    return results.groups()

# what if I only need the first step letter?

# could use indexing
first_step = decode(string)[0]

# or use throwaway variable
first_step, _  = decode(string)