4

Suppose I have a very simple function:

def myFunction(arg1, arg2):
    return arg1, arg2

Now if I only want to access the second argument, can do I something like:

none, arg2 = myFunction(arg1, arg2)

?

1
  • @AswinMurugesh since sometimes he might need the other argument as well, but other times it is not needed Commented Nov 29, 2013 at 13:58

2 Answers 2

12

Yes, yes you can do something like that. Exactly that, actually.

Assign the argument you want to ignore to a name you then simply not use anywhere else. The _ name is often used:

_, arg2 = myFunction(arg1, arg2)

The _ name is just a convention, but most Python developers understand it to mean 'this variable will be ignored by the rest of the code, it is just there to fulfill a tuple assignment'.

Alternatively, index or slice the output:

arg2 = myFunction(arg1, arg2)[-1]

or for a function with more than two return values:

arg2, arg3 = returnsMoreThanTwo(arg1, arg2)[-2:]

but if you wanted to ignore an argument in the middle somewhere, the _ assignment is best. You can use it multiple times without penalty:

arg1, _, _, arg4 = returnsFourArguments(arg1, arg2)
Sign up to request clarification or add additional context in comments.

2 Comments

Or where missing out a lot of stuff in the middle...first_and_something = operator.itemgetter(0, 60) then first, something = first_and_something(returnsWhateverArguments(arg1, arg2)) or whatever...
@JonClements: In such cases, just assigning the output to a local, then picking out specific indices would be a little more readable. Unless you need to do this for 3 or more different function calls. Then the itemgetter() approach is fair game. :-P
4
_, arg2 = myFunction(arg1, arg2)

12 Comments

Who downvoted this? It's a valid, correct answer. It's the same as Martijn's but was posted only a few seconds after.
A downvote and a delete vote... wow
@Ellioh: but it did include an explanation of why _ can be used. Not that I voted on your post..
@MartijnPieters That's maybe a reason not to upvote, but not a valid reason to downvote imho.
+1 from me. Actually, I've seen this rate of meaningless downvotes only in python questions. Never seen something like this in postgresql or sql-server. Don't know why. OTOH, it works for upvotes too - once I had answer about how to join list into string (like ' '.join(a)) with 11 upvotes!!! To get 11 upvotes in sql-server section I have to create something really cool :)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.