Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting the a value from a tuple when the other values are unused

Tags:

python

I have a tuple foo which contains something I don't care about and something I do.

foo = (something_i_dont_need, something_i_need)

Is it more correct to use

_, x = foo

or

x = foo[1]

The only things I can think of are different behaviour if foo isn't of length two. I suppose this is fairly case-specific, but is one of these the de-facto pythonic way of doing things?

like image 731
Jamie Wong Avatar asked Feb 25 '11 20:02

Jamie Wong


2 Answers

I think the usual way of doing it

x=foo[index]

Using _ is less common, and I think also discouraged. Using _ is also unwieldy when you need only a few elements out of a long tuple/list. Slicing also comes handy when you are only choosing a contiguous subsequence.

But at the end of the day I think it is just a matter of subjective preference. Use whatever that looks more readable to you and your team.

like image 66
MAK Avatar answered Sep 22 '22 05:09

MAK


I've been using _ for over a decade. It is much more readable, especially when extracting more than one value:

  _, _, name, _, _, city, _ = whatever

Even with only one variable, the other way forces humans readers to count if they want to truly understand the code, and more likely their eyes are just going to pass over it.

With the underscores, you can leverage the human brain's pattern matching abilities a little better. Probably a small thing, but every little bit helps when you're debugging. :)

like image 28
tangentstorm Avatar answered Sep 21 '22 05:09

tangentstorm