9

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?

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283

3 Answers3

24

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.

Lior
  • 2,531
  • 1
  • 15
  • 15
  • I just tested this out, and it doesn't work. Unfortunately it doesn't get away from the initial list. – Jason Wirth Mar 31 '13 at 14:43
  • The example in the question works. What exactly did you try to do? – Lior Apr 10 '13 at 11:49
  • My apologies, I tried it again and it works. I'm not sure why it didn't work before; all I can think is that I left the `,` out after `value`. – Jason Wirth Apr 12 '13 at 06:28
10
>>> t = [("asdf", )]
>>> t[0][0]
'asdf'
Umang
  • 5,196
  • 2
  • 25
  • 24
0

Try [(val, )] = t

In [8]: t = [("asdf", )]

In [9]: (val, ) = t

In [10]: val
Out[10]: ('asdf',)

In [11]: [(val, )] = t

In [12]: val
Out[12]: 'asdf'

I don't think there is a clean way to go about it.

val = t[0][0] is my initial choice, but it looks kind of ugly.

[(val, )] = t also works but looks ugly too. I guess it depends on which is easier to read and what you want to look less ugly, val or t

I liked Lior's idea that unpacking the list and tuple contains an assert.

In [16]: t2 = [('asdf', ), ('qwerty', )]

In [17]: [(val, )] = t2
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-73a5d507863a> in <module>()
----> 1 [(val, )] = t2

ValueError: too many values to unpack
Jason Wirth
  • 745
  • 1
  • 10
  • 17