Search code examples
pythoniterable-unpacking

Expand only some tuple elements to variable list


Say I have the following code:

from urlparse import urlparse
parsed_url = urlparse(url)
scheme, netloc, path = parsed_url[0], parsed_url[1], parsed_url[2]

Is there a more elegant or short way of assigning those three variables? It looks a bit messy to write parsed_url three times (I am expecting something other than renaming parsed_url to something shorter).


Solution

  • You can cut the tuple in half:

    scheme, netloc, path = parsed_url[:3]
    

    Or, to make it explicit that there are six values and you're ignoring three of them, you could assign to a dummy variable named _:

    scheme, netloc, path, _, _, _ = parsed_url