On Wed, 25 Nov 2015 02:17 am, Chris Angelico wrote: > On Wed, Nov 25, 2015 at 2:03 AM, Antoon Pardon > <antoon.par...@rece.vub.ac.be> wrote:
>> So are you saying >> >> () isn't a literal >> >> because >> >> (x * x for x in range(int(input("How far? ")))) isn't a literal? > > I'm pretty sure tuple/list/dict display predates comprehensions, and > was already not a literal syntax. Steven, you know the history better > than I do - confirm or deny? I must admit that I'm often guilty of referring to [a, b, c] as a list literal, but, no, () and related forms aren't literals[1], and yes, tuple/list/dict displays predates list comprehensions by a long time. Here's Python 1.5: Python 1.5.2 (#1, Aug 27 2012, 09:09:18) [GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> import dis >>> code = compile("(1, 2, 3)", "", "eval") >>> dis.dis(code) 0 SET_LINENO 0 3 LOAD_CONST 0 (1) 6 LOAD_CONST 1 (2) 9 LOAD_CONST 2 (3) 12 BUILD_TUPLE 3 15 RETURN_VALUE So you can see the tuple actually gets assembled at runtime. Even if the tuple is empty, the same process occurs: >>> code = compile("()", "", "eval") >>> dis.dis(code) 0 SET_LINENO 0 3 BUILD_TUPLE 0 6 RETURN_VALUE In contrast, using an actual literal (even a big one) loads the literal as a pre-existing constant: >>> code = compile("42000009999999999L", "", "eval") >>> dis.dis(code) 0 SET_LINENO 0 3 LOAD_CONST 0 (42000009999999999L) 6 RETURN_VALUE [1] Although with recent versions of Python, the peephole optimizer is clever enough to treat tuples consisting of nothing but literals as if it were itself a literal. E.g. in Python 3.3: py> import dis py> code = compile("(1, 2, 3)", "", "eval") py> dis.dis(code) 1 0 LOAD_CONST 3 ((1, 2, 3)) 3 RETURN_VALUE But that is a recent optimization, and it relies on the facts that tuples are immutable, and that the items within the tuple are themselves immutable literals: py> code = compile("(1, 2, [])", "", "eval") py> dis.dis(code) 1 0 LOAD_CONST 0 (1) 3 LOAD_CONST 1 (2) 6 BUILD_LIST 0 9 BUILD_TUPLE 3 12 RETURN_VALUE -- Steven -- https://mail.python.org/mailman/listinfo/python-list