Suppose I have a tuple in a list like this:
>>> t = [("asdf", )]
I know that the list always contains one 1-tuple. Currently I do this:
>>> dummy, = t
>>> value, = dummy
>>> value
'asdf'
Is there a shorter and more elegant way to do this?
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.
Unpack a nested tuple and list. You can also unpack a nested tuple or list. If you want to expand the inner element, enclose the variable with () or [] .
In python tuples can be unpacked using a function in function tuple is passed and in function, values are unpacked into a normal variable. The following code explains how to deal with an arbitrary number of arguments. “*_” is used to specify the arbitrary number of arguments in the tuple.
Try
(value,), = t
It's better than t[0][0]
because it also asserts that your list contains exactly 1 tuple with 1 value in it.
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