[Tutor] list semantics

Mark Lawrence breamoreboy at yahoo.co.uk
Sat Apr 11 21:20:14 CEST 2015


On 11/04/2015 20:02, Steven D'Aprano wrote:
> On Sat, Apr 11, 2015 at 10:41:28AM -0700, Jim Mooney wrote:
>> Why does the first range convert to a list, but not the second?
>>
>>>>> p = list(range(1,20)), (range(40,59))
>>>>> p
>> ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
>>   range(40, 59))
>
> Why would the second convert to a list? You don't call list() on it.
>
> You create a tuple, p, with two items. The first item is:
>
> list(range(1, 20))
>
> and the second item is:
>
> range(40, 59)
>
> so you end up with p being a tuple ([1, 2, 3, ..., 19], range(40, 59)).
>
> The fact that you surround the second item with round brackets
> (parentheses) means nothing -- they just group the range object on its
> own. A bit like saying 1 + (2), which still evaluates as 3.
>

To follow up the tuple is created with a comma *NOT* parenthesis.  So in 
the example it is the second comma, the one immediately after the call 
to list(), that makes p a tuple.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list