PythonPython Variables and Data TypesPython data types

What are the built-in data types in Python?

Question 31 of 88 · Updated

On this page

Python's built-in data types are the types provided directly by the language and its built-in namespace for representing numbers, text, sequences, mappings, sets, binary data and other values. They let developers model common kinds of information without installing external packages.

Every Python object has an identity, type and value. A name can refer to objects of different types during execution, but the type of an object determines the operations it supports.

1. Overview of the main built-in data types#

Loading diagram…

The diagram groups common types by practical use. These are not mutually exclusive groups or a formal inheritance hierarchy: for example, str and bytes are also sequence types, and bool is a subclass of int. Python has additional built-in types for functions, classes, iterators, slices and other runtime objects.

TypeExampleMutabilityTypical purpose
int42ImmutableWhole numbers
float3.5ImmutableFloating-point calculations
complex2+3jImmutableComplex arithmetic
boolTrueImmutableLogical values
str'Python'ImmutableUnicode text
list[1, 2]MutableOrdered collections
tuple(1, 2)ImmutableFixed sequences of references
rangerange(5)ImmutableArithmetic sequences of integers
dict{'id': 1}MutableKey-value associations
set{1, 2}MutableUnique hashable elements
frozensetfrozenset({1, 2})ImmutableImmutable sets
bytesb'abc'ImmutableBinary data
bytearraybytearray(b'abc')MutableEditable binary buffers
memoryviewmemoryview(b'abc')Depends on backing bufferBuffer access without an ordinary data copy
NoneTypeNoneImmutableAbsence of a value

A memoryview can expose a read-only or writable view depending on its underlying buffer and view configuration. A tuple cannot change which objects its positions refer to, but those objects may themselves be mutable.

2. How do you identify a value's type?#

Use the built-in type function to inspect an object's runtime type.

PYTHON
values = [42, 3.5, 2+3j, True, 'Python', None] for value in values: print(type(value).__name__)

Output:

int
float
complex
bool
str
NoneType

No declaration is required before binding a name to one of these objects. The previous variables lesson explains name binding and rebinding; this lesson focuses on the values and their types.

3. Numeric types: int, float, complex and bool#

Integers#

The int type represents whole numbers, including negative values and zero. Python integers support arbitrary precision subject to available resources, rather than being restricted to a fixed machine-word range.

Floating-point numbers#

The float type represents floating-point numbers. On typical CPython systems, it uses binary double precision. Many decimal fractions cannot be represented exactly. For financial or exact decimal calculations, consider the standard-library decimal module with an appropriate precision and rounding policy.

Complex numbers#

The complex type represents numbers with real and imaginary components. Python uses j for the imaginary part in literals.

Boolean values#

The bool type has the two instances True and False. It is a subclass of int, although Boolean values should normally represent logical conditions rather than numerical quantities.

PYTHON
print(7 // 2, 7 / 2) print((2 + 3j).real, (2 + 3j).imag) print(isinstance(True, int))

Output:

3 3.5
2.0 3.0
True

The division operators have different semantics. For these integer operands, // produces an integer floor-division result, while / produces a floating-point result. The complex number has real and imaginary components represented as floats.

Dedicated lessons later in this module cover numeric precision, complex numbers and Boolean behaviour in more depth.

4. Text: str#

A str represents an immutable sequence of Unicode code points. It supports indexing, slicing, searching, concatenation and many other text operations.

PYTHON
text = 'Python' print(text[0], text[-1]) print(text[1:4])

Output:

P n
yth

Index zero selects the first element, negative index -1 selects the last, and the slice starts at index 1 and excludes index 4.

A string index does not necessarily select a complete visually perceived character. Some human-readable characters consist of multiple Unicode code points. Text is distinct from encoded binary data.

5. Sequence types: list, tuple and range#

Lists are ordered, mutable sequences that can contain references to objects of different types. They are useful for collections whose contents change.

Tuples are ordered, immutable sequences. They are useful for fixed groups of values, such as coordinates or records with a known structure. A tuple is hashable only when all its elements are hashable.

A range represents an arithmetic sequence of integers without storing a separate integer object for every element in the sequence. It is commonly used for iteration.

PYTHON
items = ['pen', 'book'] items.append('bag') point = (3, 4) print(items) print(point[0], point[1]) print(list(range(2, 8, 2)))

Output:

['pen', 'book', 'bag']
3 4
[2, 4, 6]

The range begins at 2, increases by 2 and excludes the stop value 8. Calling list on it materializes the sequence into a list, which uses memory proportional to the number of generated elements.

Use a list when you need to append or replace elements, a tuple for an immutable sequence of references, and range for an arithmetic progression. The earlier list-versus-tuple lesson provides a more detailed direct comparison.

6. Mapping type: dict#

A dictionary maps hashable keys to values. Values can be arbitrary Python objects. Dictionaries preserve insertion order as a language guarantee in Python 3.7 and later.

PYTHON
stock = {'pen': 4, 'book': 2} stock['pen'] += 1 print(stock['pen']) print(list(stock)) print(stock.get('bag', 0))

Output:

5
['pen', 'book']
0

The key pen identifies a quantity, and the assignment updates the corresponding value. Iterating over the dictionary produces its keys in insertion order. The get method supplies a default for a missing key without inserting that key.

Lists are unhashable and cannot serve as ordinary dictionary keys. A tuple can be a key when its contents satisfy the hashability requirement. Equal hashable keys must have equal hashes; hashability is not simply another word for immutability.

7. Set types: set and frozenset#

A set stores distinct hashable elements. Sets are useful for membership checks, removing duplicates and operations such as union, intersection and difference.

A frozenset is immutable and hashable. It can be used as a dictionary key or a member of another set when that representation is appropriate.

PYTHON
tags = {'python', 'sql', 'python'} print(sorted(tags)) print('python' in tags) print(frozenset({1, 2}) == {1, 2})

Output:

['python', 'sql']
True
True

The repeated python element appears only once. The sorted call provides deterministic display for these comparable strings; the set itself does not guarantee iteration order.

Use set() to construct an empty set. The literal {} constructs an empty dictionary, not an empty set.

8. Binary data: bytes, bytearray and memoryview#

Binary types are important for file handling, networking, image processing and interactions with low-level buffers.

  • bytes represents an immutable sequence of byte values.
  • bytearray provides a mutable sequence of bytes.
  • memoryview exposes data through Python's buffer protocol, allowing access to supported underlying buffers without making an ordinary copy of their data.
PYTHON
raw = 'café'.encode('utf-8') print(len(raw), raw.decode('utf-8')) buffer = bytearray(b'abc') view = memoryview(buffer) view[0] = 65 print(bytes(buffer)) view.release()

Output:

5 café
b'Abc'

The Unicode string contains four code points, but its UTF-8 representation occupies five bytes. Encoding transforms text into bytes; decoding interprets bytes as text according to an encoding.

The memoryview refers to the writable bytearray buffer. Updating the view changes the underlying buffer. The integer 65 is the byte value for ASCII A.

Not every buffer is writable. A memoryview of bytes is read-only. Exported views can also restrict resizing of a backing buffer while the view exists. Manage the view's lifetime carefully.

9. NoneType and truth values#

None is the singleton instance of NoneType. It commonly represents an absent result, missing optional value or a function that returns without an explicit value.

Boolean conversion is a separate concept. Several types define false values, including zero, empty sequences, empty mappings and None.

PYTHON
print(bool(0), bool([]), bool('0')) print(None is None)

Output:

False False True
True

The string '0' is nonempty, so its Boolean value is True. Do not assume bool parses strings such as 'false' or '0' into their human-readable logical meanings.

None is not the same as zero, False or an empty collection. When specifically checking for None, use is None rather than a general truthiness check.

10. Mutable and immutable objects#

Mutability describes whether an object can be changed after it is created. It is not a property of a variable's ability to be reassigned.

PYTHON
a = [1, 2] b = a b.append(3) print(a) x = (1, 2) y = x + (3,) print(x, y)

Output:

[1, 2, 3]
(1, 2) (1, 2, 3)

The list can be modified through either reference. The tuple concatenation produces a resulting tuple without modifying the original tuple's positions.

This distinction influences copying, function arguments, shared state and dictionary keys. The next dedicated lesson examines mutability and its subtleties in detail.

11. Choosing the right data type#

RequirementSuitable starting type
Count completed tasksint
Represent an approximate physical measurementfloat
Represent a logical conditionbool
Store a person's namestr
Maintain a changing ordered collectionlist
Represent a fixed coordinate pairtuple
Iterate over consecutive integersrange
Look up records by unique identifiersdict
Track distinct tags or visited nodesset
Represent an immutable collection of unique elementsfrozenset
Read or transmit encoded binary databytes
Edit an in-memory binary bufferbytearray
Represent a missing optional resultNone

Choosing an appropriate data type can make an algorithm simpler and more efficient. For example, membership in an ordinary list can require O(n) equality comparisons, whereas dictionary and set lookup are typically expected O(1) with suitably distributed hashes, under conventional cost assumptions. Worst-case lookup and the cost of hashing or equality can be greater. These performance characteristics are not universal guarantees for all Python implementations or all user-defined objects.

12. Type conversion#

Built-in constructors and conversion functions can create values of a desired type.

PYTHON
print(int('42')) print(float('3.5')) print(list('abc')) print(sorted(set([3, 1, 3])))

Output:

42
3.5
['a', 'b', 'c']
[1, 3]

Conversion is not guaranteed to succeed or preserve all information. For example, int('hello') raises ValueError, converting a float to an integer discards its fractional part toward zero, and converting a list to a set discards duplicates and does not preserve a sequence-order contract.

Choose conversion based on the desired semantics, not merely to suppress a type error. Later lessons cover implicit and explicit conversion separately.

13. Practical example: summarising an order#

PYTHON
orders = [{'product': 'pen', 'quantity': 3, 'price': 20}, {'product': 'book', 'quantity': 2, 'price': 50}] total = sum(row['quantity'] * row['price'] for row in orders) products = {row['product'] for row in orders} print(total) print(sorted(products))

Output:

160
['book', 'pen']

This small example combines several types: a list stores the order records, dictionaries associate named fields with values, strings identify products, integers represent quantities and prices, and a set stores distinct product names.

With n rows and u distinct products, the total calculation and set construction take expected O(n) work under fixed-cost arithmetic and ordinary hash-table assumptions. Sorting the distinct names adds O(u log u) comparison work, ignoring variable string-comparison costs. The set and sorted result require O(u) additional space.

The example assumes valid quantities and prices in a single whole monetary unit. Production order processing would require schema validation, currency and rounding rules, and appropriate error handling.

14. Exact type checks versus isinstance#

PYTHON
print(type(True) is bool) print(isinstance(True, int)) print(isinstance('abc', str))

Output:

True
True
True

The exact type of True is bool, but bool inherits from int. isinstance recognizes subclass relationships. For an ordinary API accepting integer values, this distinction can matter when Boolean values should not be accepted.

Use isinstance where subclass-aware checks are appropriate. Avoid unnecessary exact-type checks when an operation can support a broader interface. Runtime type checking and static type annotations address different concerns.

15. Common mistakes#

MistakeBetter understanding
Treating {} as an empty setUse set()
Treating tuples as deeply immutableReferenced objects can be mutable
Assuming set iteration order is fixedSort comparable elements for deterministic display
Using a list as a dictionary keyKeys must be hashable
Confusing str and bytesUse explicit encoding and decoding
Assuming bool('False') is FalseA nonempty string is truthy
Using float for exact decimal money without a rounding policyConsider integer minor units or Decimal
Assuming None and zero are equivalentHandle absence explicitly

Three additional negative tests confirmed TypeError for a list used as a dictionary key, ValueError for int('hello'), and TypeError for assigning into a tuple.

Interview-ready answer#

Python's common built-in data types include numeric types int, float, complex and bool; text type str; sequence types list, tuple and range; mapping type dict; set types set and frozenset; binary types bytes, bytearray and memoryview; and NoneType, whose sole instance is None. Lists, dictionaries, sets and bytearrays are mutable, whereas integers, strings, tuples, ranges, bytes and frozensets are immutable. Objects have types, and variables are names bound to those objects. The right type depends on requirements such as ordering, uniqueness, lookup, mutability, precision and representation.

Official references#

Verification note: All twelve runnable Python examples were executed in isolated namespaces using Python 3.13.5 and their outputs matched expectations. Three additional expected-exception tests passed. The Mermaid flowchart uses standard fenced syntax and was reviewed for valid node identifiers, connections and labels; an installed Mermaid parser or site renderer was not available in the local environment. The official reference links are provided under the authorised offline research exception; live documentation and public site rendering were not checked.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design