4

How to do the opposite of this?

I have a list of namedtuples that I built by iterating a pandas dataframe:

list = []
for currRow in dataframe.itertuples():
    list.append(currRow)

How to convert this list of namedtuples into a list of tuples? Note that itertuples() returns namedtuples.

PlsWork
  • 1,958
  • 1
  • 19
  • 31
  • 4
    A named tuple *is* a tuple; the type returned by `namedtuple` is a subclass of `tuple`, and a named-tuple value should be usable anywhere a `tuple` value is expected. – chepner Apr 11 '19 at 13:17
  • @chepner Pickling a list of namedtuples fails, but pickling a list of tuples works: https://github.com/dask/dask/issues/1382. "namedtuples aren't serializable under cloudpickle" – PlsWork Apr 11 '19 at 13:19
  • 1
    That's unfortunate; sounds like a bug. `T = namedtuple("T", "foo bar"); t = T(1,2); pickle.dumps(t)` produces `b'\x80\x03c__main__\nT\nq\x00K\x01K\x02\x86q\x01\x81q\x02.'`. – chepner Apr 11 '19 at 13:26

3 Answers3

9

You just put it through the tuple() constructor:

>>> from collections import namedtuple

>>> foo = namedtuple('foo', ('bar', 'baz'))
>>> nt = foo(1,2)
>>> nt
foo(bar=1, baz=2)
>>> tuple(nt)
(1, 2)
deceze
  • 510,633
  • 85
  • 743
  • 889
2

First, don't name your variables after builtins.

To answer your question, you can just use the tuple constructor; assuming your source list is named l:

l_tuples = [tuple(t) for t in l]
gmds
  • 19,325
  • 4
  • 32
  • 58
1

You can do this. Just construct the tuple from the namedtuple as param.

>>> X = namedtuple('X', 'y')
>>> x1 = X(1)
>>> x2 = X(2)
>>> x3 = X(3)
>>> x_list = [x1, x2, x3]
>>> x_tuples = [tuple(i) for i in x_list]
>>> x_tuples
[(1,), (2,), (3,)]
>>> 
scarecrow
  • 6,624
  • 5
  • 20
  • 39