[Tutor] don't understand iteration

Alan Gauld alan.gauld at btinternet.com
Tue Nov 11 11:52:50 CET 2014


On 11/11/14 04:45, Clayton Kirkwood wrote:

>>> *list(range(1,6))
>    File "<input>", line 1
> SyntaxError: can use starred expression only as assignment target

list() is a function. You cannot unpack a function.

Also the * operator needs to be used inside a function parameter list.
(There may be some obscure case where you can use it outside of that but 
99% of the time that's the only place you'll see it used.)

>>>> a = list(*range(5))

And again range() is a function, you can only use * on a list/tuple.

>>>> a = list(range(*5))

And here 5 is an integer. It must be a sequence.

> As far as I can tell, everything that has been suggested doesn't work:

What has been suggested is a collection inside a functions argument 
list. You haven't tried that in any of your examples.

Here are a couple of valid cases:

 >>> def threeArgs(a,b,c):
...    print(a,b,c)
...
 >>> myList = [3,5,8]
 >>>
 >>> threeArgs(*myList)    # unpack a variable
3 5 8
 >>> threeArgs(*(9,3,1))   # unpack literal tuple
9 3 1

> Has to be only in assignment target,

I agree the error message is not at all clear.
Its probably technically correct from the interpreters perspective
but its not that clear to the programmer.

> Perhaps the vaunted try it in the console, doesn't work.

It does work as I showed above. But you still need to type in
the right syntax.

> I am sure that I am missing something

The fact that it only works inside a function's argument list.

>> And the link to Calls:
>>
>> https://docs.python.org/3/reference/expressions.html#calls
>>
>> which says:
>> --------------
>> ...
>> If the syntax *expression appears in the function call, expression must
>> evaluate to an iterable. Elements from this iterable are treated as if
>> they were additional positional arguments;

That's the explanation right there.
It says that if you call a function and use *name in the argument list 
Python will expect name to refer to an iterable and will unpack the 
iterables elements(values) and use them as positional arguments in
the function call. Like most of the Python docs its accurate but terse.

> Yes, inside the call to a function call.
 > My question is outside to a function call.

You cannot use the * operator outside a function call.
At least I can't think of a case where it works.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list