How to ignore the rest of the parameters that return by the function?

Viewed 204
def get():
   ...
   ...
   return x,y,z

a,b,c = get()

i don't need b, c is there a solution to ignore them (something like don't care)

3 Answers

The recommended way of doing this is to use the _ variable name, as indicated by Abdul Niyas P M, this will not store the values captured by the _.

x, _, z = 1, 2, 3 # if x and z are necessary
# or
x, *_ = 1, 2, 3   # if only x is necessary

You might have noticed that if you just do something like a = get() Python will throw all 3 values into the variable 'a' as a tuple.

The best and simplest solution possible at the moment (in the current python version 3.8) is to simply create a second variable to throw stuff in and not ever use that variable. For example:

a, b = get()

However some people like to use a variable named *_ to indicate that this value is trash and needs to be ignored (The variable name adds nothing special, its just a convention to indicate we wont use it source)

a, *_ = get()

Let's say, within the returned tuple of values, you are interested only in the k th value.

You could then do:

a = get()[k]

assuming of course, that we're counting k from 0 (and not from 1)

Related