Eye of Hell Eye of Hell - 3 months ago 30
Python Question

Partial list unpack in Python

In Python, the assignment operator can unpack list or tuple into variables, like this:

l = (1, 2)
a, b = l # Here goes auto unpack


But I need to specify exactly the same amount of names to the left as an items count in the list to the right. But sometimes I don't know a size of the list to the right, for example if I use split(). Example:

a, b = "length=25".split("=") # This will result in a="length" and b=25


But the following code will lead to an error:

a, b = "DEFAULT_LENGTH".split("=") # Error, list has only one item


Is it possible to somehow unpack list in the example above so I get a = "DEFAULT_LENGTH" and b equals to 'None' or not set? A straightforward way looks kind of long:

a = b = None
if "=" in string :
a, b = string.split("=")
else :
a = string

Answer
# this will result in a="length" and b="25"
a, b = "length=25".partition("=")[::2]

# this will result in a="DEFAULT_LENGTH" and b=""
a, b = "DEFAULT_LENGTH".partition("=")[::2]