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")
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With