23

What exactly is a literal in python? I searched for the answer on google, and in the python docs, but google just references to string literals, and the python docs don't explicitly state what a literal is. I came across this page http://www.dalkescientific.com/writings/NBN/python_intro/literals.html that provided the following answer:

Objects are also called data structures. Python comes with some built-in objects. Some are used so often that Python has a quick way to make these objects, called literals. The literals include the string, unicode string, integer, float, long, list, tuple and dictionary types.

Is this correct? Can I assume that literals are just another term for python's built-in objects? Are there any more literals that were not covered in the description? I was under the impression that there was such a thing as a binary literal, and that booleans were also considered literals.

citizenzer0
  • 349
  • 1
  • 2
  • 6
  • The difference refers to the constructor - see [here for a `dict` example](http://stackoverflow.com/questions/6610606/is-there-a-difference-between-using-a-dict-literal-and-a-dict-constructor) that carries over. – Stefan Dec 09 '15 at 21:18
  • 2
    A literal is something that is defined in the specification of the languages syntax that creates certain data types. Because of this you can't rename it or change it. Consider the difference between `[]` and `list()` the former always creates a list whereas the latter has to look up what `list` is which as a default will construct a list but does not necessarily do if `list` was reassigned elsewhere. – shuttle87 Dec 09 '15 at 21:19
  • 2
    This question was much better for me than the one "already answered", and more importantly, **different** to that one. As people looking for this questions don't necessarily know - indeed most probably don't- that Literal and Literal constants are basically the same. – Martin Feb 09 '17 at 01:10

4 Answers4

38

A literal is something that the parser recognizes as syntax for writing an object directly. Some examples in Python 2:

  • 0, 1, 2, 3 (int literals)
    • -1, -2, etc are not literals themselves, but expressions involving the unary - operator.
  • 5j, 3.14j (non-negative pure imaginary complex literals)
    • Other complex values, like 2+3j, 2-3j, and -5j, are expressions involving various operators.
  • 3.5, -2.7 (float literals)
  • "", "hello" (str literals)
  • u"", u"hello" (unicode literals)
  • None (I think this is considered a literal, and not a keyword or simple name.)

Other literal-like expressions called displays are used to create various containers. They aren't true literals because they can contain non-literal expressions (e.g., [x, y]).

  • [], [1,2] (list displays)
  • (), (1,), (1,2) (tuple displays)
  • {}, {'a': 2} (dict displays)
  • {1,2,3} (set display introduced in Python 2.7)

There is no literal or display for an empty set, as the obvious notation {} is already a dict display. Python 2 does not have true Boolean literals; True and False are simply built-in names for the Boolean objects. A tuple is technically created by the comma, and the parentheses are only necessary when you need to disambiguate the expression; the exception is the empty tuple ().

See phihag's answer for some differences in Python 3.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    Thank you, this explained it well! – citizenzer0 Dec 09 '15 at 21:36
  • This and phihag's have clarified what is a literal for once... after so much searching... thanks! – Martin Feb 09 '17 at 01:14
  • I don't believe `-3` is an integer literal in Python. It's an expression: the unary negation operator applied to the integer literal `3`. The same is true for floating point literals. In fact, you can demonstrate this: `-2**2` is `-(2**2)`, i.e. `-4`, as opposed to `(-2)**2` which would be `4`. – Tom Karzes Mar 29 '20 at 08:06
  • Similarly, Python does not have complex literals. It only has non-negative imaginary literals. These can be combined with floating point literals to form complex numbers. So `-3-5j` is actually `(-(3))-(5j)`. There are two literals in this expression: `3` and `5j`. – Tom Karzes Mar 29 '20 at 08:09
  • I cleaned this answer up a bit, as well as adding the distinction between true literals and *displays* (used to create lists et al.). – chepner Mar 29 '20 at 19:37
18

literal is a language-independent programming term. A literal is a succinct and easily visible way to write a value. For example, you could construct the value zero with int(), but 0 is much more convenient.

In Python, the following literals are available:

  • Character string literals, such as 'Düsseldorf', u'Köln' (the first one is a byte string literal in Python 2.x)
  • Byte string literals such as b'\x89PNG'
  • Integer literals such as 42, 1_234, 0x2a or 0b101010
  • Float literals such as 1.2e-19
  • Imaginary literals such as 2.3j
  • Boolean literals: True and False (not literals in older (2.x) Python versions)
  • None
  • Tuples: (1, 2, 3)
  • Lists: [1, 2, 3]
  • Dicts: {1: 'one', 2: 'two'}
  • Sets: {1, 2, 3}
phihag
  • 278,196
  • 72
  • 453
  • 469
  • 2
    Thanks! First example that makes it more than just something different to a variable... +++++ – Martin Feb 09 '17 at 01:12
  • 1
    I don't believe `-12` is an integer literal in Python. It's an expression: the unary negation operator applied to the integer literal `12`. The same is true for floating point literals. In fact, you can demonstrate this: `-2**2` is `-(2**2)`, i.e. `-4`, as opposed to `(-2)**2` which would be `4`. – Tom Karzes Mar 29 '20 at 07:35
  • Similarly, Python does not have complex literals. It only has non-negative imaginary literals. These can be combined with floating point literals to form complex numbers. So `1+2.3j` is actually `(1)+(2.3j)`. There are two literals in this expression: `1` and `2.3j`. – Tom Karzes Mar 29 '20 at 08:10
  • @TomKarzes Good points. Fixed. – phihag Mar 29 '20 at 13:29
  • You should change "complex literals" to "imaginary literals". Imaginary literals do have type complex, but their real part is always zero. Arbitrary complex numbers are formed by adding a float (or int) to an imaginary literal. This comes straight from the Python documentation: [Imaginary literals](https://docs.python.org/3/reference/lexical_analysis.html#imaginary-literals) – Tom Karzes Mar 29 '20 at 14:49
  • "Object" literasl: https://stackoverflow.com/questions/3335268/are-object-literals-pythonic – NeilG Mar 21 '23 at 01:58
2

In this context, I think it just means that the Python parser accepts a built-in syntax for these entities. For instance, "abc" is a str, 123 is an int, 1.2 is a float, etc.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
2

Can I assume that literals are just another term for python's built-in objects?

Close. They are a way of writing (some of) Python's built-in objects. If you need, say, a particular number, and you are not reading it from a file or from the user or getting it from a database or calculating it or importing it from another module or or or... you can use a numeric literal to put it right there in your code.

number = 42

number here is the integer 42, specified by using a literal.

Python's True and False values (and None) are not really literals, but predefined names for those values. But the concept is similar: Python is giving you a way to write those values directly into your code.

Nearly all programming languages have literals for most of their frequently-used types.

kindall
  • 178,883
  • 35
  • 278
  • 309