Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpacking a 1-tuple in a list of length 1

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?

like image 841
Björn Pollex Avatar asked Jul 10 '10 14:07

Björn Pollex


People also ask

How do I unpack a tuple in a 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.

Does tuple unpacking work with lists?

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 [] .

Is unpacking possible in a tuple?

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.


1 Answers

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.

like image 64
Lior Avatar answered Nov 03 '22 09:11

Lior