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.
Literals in Python is defined as the raw data assigned to variables or constants while programming. We mainly have five types of literals which includes string literals, numeric literals, boolean literals, literal collections and a special literal None.
Python has one special literal called 'None'. The 'None' literal is used to indicate something that has not yet been created. It is also used to indicate the end of lists in Python.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With