Introduction to types

Published

2023-08-02

What are types?

Consider the universe of wheeled motor vehicles. There are many types: motorcycles, mopeds, automobiles, sport utility vehicles, busses, vans, tractor-trailers, pickup trucks, all-terrain vehicles, etc., and agricultural vehicles such as tractors, harvesters, etc. Each type has characteristics which distinguish it from other types. Each type is suited for a particular purpose (you wouldn’t use a moped to do the work of a tractor, would you?).

Similarly, everything in Python has a type, and every type is suited for a particular purpose. Python’s types include numeric types such as integers and floating-point numbers; sequences such as strings, lists, and tuples; Booleans (true and false); and other types such as sets, dictionaries, ranges, and functions.

Why do we have different types in a programming language? Primarily for three reasons.

First, different types have different requirements regarding how they are stored in the computer’s memory (we’ll take a peek into this when we discuss representation).

Second, certain operations may or may not be appropriate for different types. For example, we can’t raise 5 to the 'pumpkin' power, or divide 'illuminate' by 2.

Third, some operators behave differently depending on the types of their operands. For example, we’ll see in the next chapter how + is used to add numeric types, but when the operands are strings + performs concatenation. How does Python know what operations to perform and what operations are permitted? It checks the type of the operands.

What’s a literal?

A literal is simply fixed values of a given type. For example, 1 is a literal. It means, literally, the integer 1. Other examples of literals follow.

Some commonly used types in Python

Here are examples of some types we’ll see. Don’t worry if you don’t know what they all are now—all will become clear in time.

Type Description Example(s) of literals
int integer 42, 0, -1
float floating-point number 3.14159, 2.7182, 0.0
str string 'Python', 'badger', 'hovercraft'
bool Boolean True, False
NoneType none, no value None
tuple tuple (), ('a', 'b', 'c'), (-1, 1)
list list [], [1, 2, 3], ['foo', 'bar', 'baz']
dict dictionary (key: value) {'cheese': 'stilton'}, {'age': 99}
function function (see: Chapter 5)

int

The int type represents integers, that is, whole numbers, positive or negative, and zero. Examples of int literals: 1, 42, -99, 0, 10000000, etc. For readability, we can write integer literals with underscores in place of thousands separators. For example, 1_000_000 is rather easier to read than 1000000, and both have the same value.

float

Objects of the float type represent floating-point numbers, that is, numbers with decimal (radix) points. These approximate real numbers (to varying degrees; see the section on representation error). Examples of float literals: 1.0, 3.1415, -25.1, etc.

str

A string is an ordered sequence of characters. Each word on this page is a string. So are "abc123" and "@&)z)$"—the symbols of a string needn’t be alphabetic. In Python, objects of the str (string) type hold zero or more symbols in an ordered sequence. Strings must be delimited to distinguish them from variable names and other identifiers which we’ll see later. Strings may be delimited with single quotation marks, double quotation marks, or “triple quotes.” Examples of str literals: "abc", "123", "vegetable", "My hovercraft is full of eels.", """What nonsense is this?""", etc.

Single and double quotation marks are equivalent when delimiting strings, but you must be consistent in their use—starting and ending delimiters must be the same. "foo" and 'foo' are both valid string literals; "foo' and 'foo" are not.

>>> "foo'
  File "<stdin>", line 1
    "foo'
    ^
SyntaxError: unterminated string literal (detected at line 1)

It is possible to have a string without any characters at all! We call this the empty string, and we write it '' or "" (just quotation marks with nothing in between).

Triple-quoted strings have special meaning in Python, and we’ll see more about that in Chapter 6, on style. These can also be used for creating multi-line strings. Multi-line strings are handy for things like email templates and longer text, but in general it’s best to use the single- or double-quoted versions.

bool

bool type is used for two special values in Python: True and False. bool is short for “Boolean”, named after George Boole (1815–1864), a largely self-taught logician and mathematician, who devised Boolean logic—a cornerstone of modern logic and computer science (though computers did not yet exist in Boole’s day).

There are only two literals of type bool: True and False. Notice that these are not strings, but instead are special literals of this type (so there aren’t any quotation marks, and capitalization is significant).1

NoneType

NoneType is a special type in Python to represent the absence of a value. This may seem a little odd, but this comes up quite often in programming. There is exactly one literal of this type: None (and indeed there is exactly one instance of this type).

Like True and False, None is not a string, but rather a special literal.

tuple

A tuple is an immutable sequence of zero or more values. If an object is immutable, this means it cannot be changed once it’s been created. Tuples are constructed using the comma to separate values. The empty tuple, (), is a tuple containing no elements.

The elements of a tuple can be of any type—including another tuple! The elements of a tuple needn’t be the same type. That is, tuples can be heterogeneous.

While not strictly required by Python syntax (except in the case of the empty tuple), it is conventional to write tuples with enclosing parentheses. Examples of tuples: (), (42, 71, 99), (x, y), ('cheese', 11, True), etc.

A complete introduction to tuples appears in Chapter 10.

list

A list is a mutable sequence of zero or more values. If an object is mutable, then it can be changed after it is created (we’ll see how to mutate lists later). Lists must be created with square brackets and elements within a list are separated by commas. The empty list, [], is a list containing no elements.

The elements of a list can be of any type—including another list! The elements of a list needn’t be the same type. That is, like tuples, lists can be heterogeneous.

Examples of lists: [], ['hello'], ’['Larry', 'Moe', 'Curly'], [3, 6, 9, 12], [a, b, c], [4, 'alpha', ()], etc.

A complete introduction to lists appears in Chapter 10.

dict

dict is short for dictionary. Much like a conventional dictionary, Python dictionaries store information as pairs of keys and values. We write dictionaries with curly braces. Keys and values come in pairs, and are written with a colon separating key from value.

There are significant constraints on dictionary keys (which we’ll see later in Chapter 16). However, dictionary values can be just about anything—including lists, tuples, and other dictionaries! Like lists, dictionaries are mutable. Example:

    {'Egbert': 19, 'Edwina': 22, 'Winston': 35}

A complete introduction to dictionaries appears in Chapter 16.

The first few types we’ll investigate are int (integer), float (floating-point number), str (string), and bool (Boolean). As noted, we’ll learn more about other types later.

For a complete reference of built-in Python types, see: https://docs.python.org/3/library/stdtypes.html

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).

Footnotes

  1. In some instances, it might be helpful to interpret these as “on” and “off” but this will vary with context.↩︎