Python is all about writing beautiful code. So, I was running pylint
to check the "beautifulness" of my code, when I bump into something:
Unused variable 'myvar1'
From this part of my code:
for myvar1, myvar2 in mylist:
# Do stuff just using myvar2
mylist
is a list of tuples, so I'm unwrapping the tuples into two variables (myvar1
and myvar2
). I'm defining those two variables just to unwrap the second one, because I don't need the other.
So, here's my question: Is there a way to tell the interpreter to unwrap the tuple, but not assing the first part (for example). In some other languages you can do something like:
for _, myvar in mylist:
# Do stuff with myvar
or
for *, myvar in mylist:
# Do stuff with myvar
That means: I don't care about the first part of the tuple, I just need the second one.
NOTE: I know that this could be an option for what I'm asking:
for mytuple in mylist:
# Do stuff with mytuple[1]
But that's by far less readable.
In addition to @RaymondHettinger's answer: Pylint also does not complain about unused variables if their names start with a single underscore. This means that you can use:
for _myvar1, myvar2 in mylist:
getting the best of both worlds:
This works for function / method prototypes too and avoids warnings about unused parameters, which you can often get when deriving from a base class in an OO framework.