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?
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.
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With