0

I've seen a lot of questions on here about using * before a tuple to expand it into something else, but it doesn't seem to work for me.

>>> l1 = (1, 2, 3)
>>> l2 = (0, l1, 4)
>>> l2   (0, (1, 2, 3), 4)
>>> l2 = (0, *l1, 4)
File "<stdin>", line 1  
    l2 = (0, *l1, 4)  
             ^   SyntaxError: invalid syntax 

As you can see. I can't get l1 to expand into l2 with the * operator...

Note: This is python2.7

Eric Fossum
  • 2,395
  • 4
  • 26
  • 50

2 Answers2

6

In-place unpacking has been introduced in python 3.5 and it works in later versions not older ones.

# Python 3.5
In [39]: (3, *l1, 4)
Out[39]: (3, 1, 2, 3, 4)

In older versions you can use + operator or itertools.chain function for longer iterables:

In [40]: (3,) + l1 + (4,)
Out[40]: (3, 1, 2, 3, 4)

In [41]: from itertools import chain

In [45]: tuple(chain((3,), l1, (4,)))
Out[45]: (3, 1, 2, 3, 4)
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

First of all, those aren't lists, they're tuples. They are similar but not the same thing.

Second, the *arg syntax is called argument expansion, and it only works for function arguments

def func(a, b):
    return a + b

my_list = [1, 2]
func(*my_list)

EDIT:

Apparently, in-place unpacking was added in python 3.5, but for the overwhelming majority of python installations you encounter, my answer still holds true. Perhaps in 2020 when Python 2 stops being supported this will change, but for now and the immediate future, expect the above to be true.

Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
  • And this is why it is important to specify your version of Python. – Mad Physicist Feb 09 '17 at 18:45
  • Thanks, though, the user is clearly using python 2. Python 3 is still in relatively little use, let alone 3.5. – Brendan Abel Feb 09 '17 at 18:45
  • 1
    While it is true that OP is clearly using something prior to version 3.5 (maybe 2, but maybe an earlier 3) and for those versions your answer is adequate, your answer is nevertheless misleading for readers of later versions of Python. At the very least, you should mention this. – John Coleman Feb 09 '17 at 18:47
  • You are needlessly snarky about Python 2 vs Python 3 (in data science , for instance, Python 3 is making rapid gains: http://ianozsvald.com/2016/06/20/results-for-which-version-of-python-2vs3-do-london-data-scientists-use/ ) but you answer is otherwise fine now, so +1. – John Coleman Feb 09 '17 at 19:06