Unpack the list in the middle of the tuple

I have a list of undefined size:

l = [...] 

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

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

How to form the following?

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

EDIT: It would be nice to just cut [a: b]:

 t = ("AA", "B", l[a], ..., l[b], "C") 
+8
python list tuples
source share
3 answers

Starting with python 3.5, now you can use your first approach:

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

You can use slices as you expected:

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

Related PEP, for reference: PEP448

+1
source share

You cannot unpack a tuple by replacing such values โ€‹โ€‹(for now - see PEP 448 ), since unpacking will occur only on the left side or, as indicated in the error message, the destination is assigned.

In addition, the target must have valid Python variables. In your case, you have string literals also in the tuple.

But you can build the tuple you need by combining three tuples, for example

 >>> 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') 
+8
source share

You can flatten the list and then convert to a 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') >>> 
0
source share

All Articles