15

The following line returns an error:

self.m, self.userCodeToUserNameList, self.itemsList, self.userToKeyHash, self.fileToKeyHash = readUserFileMatrixFromFile(x,True) 

The function actually returns 6 values. But in this case, the last one is useless (its None). So i want to store only 5.

Is it possible to ignore the last value?

2
  • 5
    Why not just add the necessary variable to unpack into? Name it unused or something. Commented Jul 28, 2016 at 12:46
  • Simply because it would look cleaner without the useless variable Commented Jul 28, 2016 at 13:51

4 Answers 4

35

You can use *rest from Python 3.

>>> x, y, z, *rest = 1, 2, 3, 4, 5, 6, 7 >>> x 1 >>> y 2 >>> rest [4, 5, 6, 7] 

This way you can always be sure to not encounter unpacking issues.

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

2 Comments

The OP only wants to discard one value, so I don't think this syntax is needed (and it's not actually discarded anyway).
I find this more generic. Maybe down the road the OP will need/want the value, or have more values to unpack... etc
11

It's common to use _ to denote unneeded variables.

a, b, c, d, e, _ = my_func_that_gives_6_values() 

This is also often used when iterating a certain number of times.

[random.random() for _ in range(10)] # gives 10 random values 

Python 3 also introduced the * for assignment, similar to how *args takes an arbitrary number of parameters. To ignore an arbitrary number of arguments, just assign them to *_:

a, b, c, d, e, *_ = my_func_that_gives_5_or_more_values() 

This can be used at any point in your assignment; you can fetch the first and last values and ignore padding in the middle:

>>> a, b, c, *_, x, y, z = range(10) >>> print(a, b, c, '...', x, y, z) 0 1 2 ... 7 8 9 

Comments

0

Just, use the throw-away variable '_'

 self.m, self.userCodeToUserNameList, self.itemsList, self.userToKeyHash, self.fileToKeyHash, _ = readUserFileMatrixFromFile(x,True) 

here '_' is deliberately ignored.

3 Comments

This is already present in two other answers, and yours is unformatted.
When I added other solutions weren't present, yet.
What I'm saying that I did not hit refresh page before submitting. My fault.
0

Just slice the last one out:

self.m, self.userCodeToUserNameList, \ self.itemsList, self.userToKeyHash, \ self.fileToKeyHash = readUserFileMatrixFromFile(x,True)[:-1] 

EDIT after TigerhawkT3's comment :

Note that this works only if the return object supports slicing.

2 Comments

This only works if the returned object supports slicing.
@TigerhawkT3 You are absolutely right. I'm not saying this is the best solution, though it may be useful to OP. And other methods have already been answered, that's why they weren't included

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.