In Python, the assignment operator can unpack a list or a 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 item count in the list to the right. But sometimes I don't know the 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 the list in the example above so I can 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
Summary. Unpacking assigns elements of the list to multiple variables. Use the asterisk (*) in front of a variable like this *variable_name to pack the leftover elements of a list into another list.
Python uses the commas ( , ) to define a tuple, not parentheses. Unpacking tuples means assigning individual elements of a tuple to multiple variables. Use the * operator to assign remaining elements of an unpacking assignment into a list and assign it to a variable.
Introduction. Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, * .
In python tuples can be unpacked using a function in function tuple is passed and in function values are unpacked into normal variable.
This may be of no use to you unless you're using Python 3. However, for completeness, it's worth noting that the extended tuple unpacking introduced there allows you to do things like:
>>> a, *b = "length=25".split("=") >>> a,b ("length", ['25']) >>> a, *b = "DEFAULT_LENGTH".split("=") >>> a,b ("DEFAULT_LENGTH", [])
I.e. tuple unpacking now works similarly to how it does in argument unpacking, so you can denote "the rest of the items" with *
, and get them as a (possibly empty) list.
Partition is probably the best solution for what you're doing however.
# 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]
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