0

I have a list of data:

[[], [], [(2, 3), (2, 7), (3, 2), (7, 2)], [(2, 3), (3, 2), (3, 7), (7, 3)], [], [], [], [(2, 7), (3, 7), (7, 2), (7, 3)], [], []]

I want to remove the brackets in the tuple so that [(2, 3), (2, 7), (3, 2), (7, 2)] will become (2,3,2,7,3,2,7,2).

Is there a shortcut to do this?

  • I don't think the dupe close is correct. OP seems to want to keep the outermost list and just unpack the inner lists. NPE has effectively answered this problem in his answer. – Ffisegydd Jan 06 '15 at 13:10

2 Answers2

3

You could use itertools.chain:

In [6]: l = [[], [], [(2, 3), (2, 7), (3, 2), (7, 2)], [(2, 3), (3, 2), (3, 7), (7, 3)], [], [], [], [(2, 7), (3, 7), (7, 2), (7, 3)], [], []]

In [7]: [tuple(itertools.chain(*el)) for el in l]
Out[7]: 
[(),
 (),
 (2, 3, 2, 7, 3, 2, 7, 2),
 (2, 3, 3, 2, 3, 7, 7, 3),
 (),
 (),
 (),
 (2, 7, 3, 7, 7, 2, 7, 3),
 (),
 ()]
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • `[tuple(itertools.chain(*el)) if el else el for el in l]` I think the empty list should not be converted to tuple object. – Tanveer Alam Jan 06 '15 at 13:09
  • @TanveerAlam: I too think that. However, I'd rather not second-guess OP's requirements (which are ambiguous on this). – NPE Jan 06 '15 at 13:10
  • `[tuple(np.array(ls).flatten()) for ls in l]` also gives us the same result. – dragon2fly Jan 06 '15 at 13:40
-1

You're looking to flatten a list. In python you can do that with a compound list comprehension

data = [(2, 3), (3, 2), (3, 7), (7, 3)]
flattend = [item for lst in data for item in lst]
Exelian
  • 5,749
  • 1
  • 30
  • 49