11

I have a list of uncertain size:

l = [...]

And I want to unpack this list into a tuple that has other values, but the below fails:

t = ("AA", "B", *l, "C")

How do I form the following?

t = ("AA", "B", l[0], ..., l[:-1], "C")

EDIT: it would also be nice to do a slice [a:b] only:

t = ("AA", "B", l[a], ..., l[b], "C")
Tommy
  • 12,588
  • 14
  • 59
  • 110

3 Answers3

10

As of python 3.5, you can now use your first approach:

>>> l = [1, 2, 3]
>>> t = ("AA", "B", *l, "C")
>>> t
('AA', 'B', 1, 2, 3, 'C')

You can use slices just as you'd expect:

>>> ("AA", "B", *l[:-1], "C")
('AA', 'B', 1, 2, 'C')

The related PEP, for reference: PEP448

fwip
  • 395
  • 3
  • 6
9

You cannot unpack into a tuple by substituting values like that (yet - see PEP 448), because unpacking will happen only on the left hand side expression or as the error message says, assignment target.

Also, assignment target should have valid Python variables. In your case you have string literals also in the tuple.

But you can construct the tuple you wanted, by concatenating three tuples, like this

>>> l = [1, 2, 3, 4]
>>> ("A", "B") + tuple(l[:-1]) + ("C",)
('A', 'B', 1, 2, 3, 'C')
>>> ("A", "B") + tuple(l) + ("C",)
('A', 'B', 1, 2, 3, 4, 'C')
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • this works as intended, thank you, though I do think the * notation should be supported as sugar because this is ugly. I guess I could write a function that does it. – Tommy Jun 09 '15 at 18:11
0

You can flatten the list and then convert to tuple.

>>> import itertools
>>> l=[1,2,3,4]
>>> t = ('A', 'B', l, 'C')
>>> t
('A', 'B', [1, 2, 3, 4], 'C')
>>> tuple(itertools.chain.from_iterable(t))
('A', 'B', 1, 2, 3, 4, 'C')
>>>
Community
  • 1
  • 1
shantanoo
  • 3,617
  • 1
  • 24
  • 37
  • this does not work when the list contains multiple character items like "abc". – Tommy Jun 15 '15 at 17:52
  • Right. That is the correct behavior. List and string both are iterable. Hence, string is also expanded, similar to list. My bad. – shantanoo Jun 16 '15 at 05:10