views:

1181

answers:

6

Say I have a Python function that returns multiple values in a tuple:

def func():
    return 1, 2

Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this:

x, temp = func()
+13  A: 

You can use x = func()[0] to return the first value, x = func()[1] to return the second, and so on.

Pourquoi Litytestdata
+19  A: 

One common convention is to use a "_" as a variable name for the elements of the tuple you wish to ignore. For instance:

def f():
    return 1, 2, 3

_, _, x = f()
Brian Clapper
Very interesting concept, but not very Pythonic. However, neither is my submitted solution. :-P May I ask, where did you hear of this convention? I'd like to learn how popular it is.
Evan Fosmark
That's the concept I've heard of before but couldn't remember. Not sure where I heard of it from though.
Mat
I've seen it in various pieces of code here and there. If you do a grep -w '_,' *.pyin the standard Python library, you'll find a few instances of it. Forexample, UserDict.py has a couple instances of it. I've also seen it in packages like Pygments and Django.
Brian Clapper
@Evan I actually find this to be very Pythonic, especially given python's propensity for using underscores. (int.__mul__, __iter__, __builtins__, etc.)
brad
It's definitely standard in the python community, I've been doing it so long I don't remember why I started doing it. I was surprised I didn't find it in PEP 8.
llimllib
-1: this "convention" sucks when you add gettext functionality to someone else's code (that defines a function called '_') so it should be banned
nosklo
Good point--though it's debatable whether gettext's insistence on installing a function called "_" is a good idea. Personally, I find it a little ugly.Regardless, the use of "_" as a throwaway variable is widespread.
Brian Clapper
This convention is also common in Haskell. Anyone know where it originated?
Kiv
This is neat. Seems to me that it comes from the Perl world.
Camilo Díaz
The origin, as far as I can tell, is ML. This is supported by the same usage in functional languages, especially ML-derived/-inspired languages such as OCaml, F#, Nemerle, etc.
Cody Brocious
-1: _ means "last output" in IPython. I would never assign something to it.
endolith
@endolith: citation needed
Draemon
@Draemon: http://ipython.scipy.org/doc/manual/html/interactive/tutorial.html#use-the-output-cache
endolith
Ok, I didn't notice the "I" - thanks for the reference. IMHO you can't expect others not to use a variable just because one Python app defines its own magical use for it.
Draemon
+3  A: 

Three simple choices.

Obvious

x, _ = func()

x, junk = func()

Hideous

x = func()[0]

And there are ways to do this with a decorator.

def val0( aFunc ):
    def pick0( *args, **kw ):
        return aFunc(*args,**kw)[0]
    return pick0

func0= val0(func)
S.Lott
I really prefer the `_` variable. It's very obvious that you're ignoring a value
Claudiu
+4  A: 

Remember, when you return more than one item, you're essentially returning a list-like object. So you can do things like this:

def func():
    return 1, 2

print func()[0] # prints 1
print func()[1] # prints 2
Evan Fosmark
"list-like object" -> "tuple"
chpwn
+1  A: 

This seems like the best choice to me:

val1, val2, ignored1, ignored2 = some_function()

It's not cryptic or ugly (like the func()[index] method), and clearly states your purpose.

Mosor
+4  A: 

If you're using Python 3, you can you use the star before a variable (on the left side of an assignment) to have it be a list in unpacking.

# Example 1: a is 1 and b is [2, 3]

a, *b = [1, 2, 3]

# Example 2: a is 1, b is [2, 3], and c is 4

a, *b, c = [1, 2, 3, 4]

# Example 3: b is [1, 2] and c is 3

*b, c = [1, 2, 3]

# Example 4: a is 1 and b is []

a, *b = [1]