unary star
VanL
vlindberg at verio.net
Tue May 6 10:20:10 EDT 2003
I like this idea -- I frequently find myself in situations where I want
to take only the first item from a list. (I usually reverse the list,
and then pop() it.)
I would vastly prefer a
first, *rest = some_list
type syntax.
> At first blush, I like the idea of unary * being more widely
> applicable.
>
> I see one difficulty: what if you want to expand a sequence of
> sequences? That is, what if you have
> S = ((c, d), (e, f))
> and want to produce
> (a, b, c, d, e, f)
> ? If unary * worked, this would (I presume) be
> (a, b, **S)
> which looks misleadingly like the **kwargs syntax. A reader might
> expect that S is a dict. Moreover, you couldn't use this in a
> function call; you'd have to add whitespace: * *S. Ick.
>
Here is the way out of that difficulty: make the unary ** only
applicable to dicts. Expanding a nested list would require a paren.
Examples:
mylist = [1,2,3]
mytuple = (1,2,3)
mydict = {'1': 1, '2': 2, '3':3}
mynestedlist = [[1,2], [3,4]]
first, *rest = mylist
print first, rest, mylist
1 [2,3] [2,3]
first, *rest = mytuple
print first, rest, mytuple
1 (2,3) (1,2,3)
first, *rest = mydict
SyntaxError: Unary * not supported for dict
enumerated = **mydict
print enumerated
[('1', 1), ('2', 2), ('3', 3)]
**mynestedlist
SyntaxError: Unary ** not supported for list
*mynestedlist
[1,2] [3,4]
*(*mynestedlist)
[1,2,3,4]
Just some ideas. I think that this might even be worthy of a PEP?
VanL
More information about the Python-list
mailing list