PythonPython Variables and Data TypesPython data types
What are the built-in data types in Python?
Question 31 of 88 · Updated
On this page
- 1. Overview of the main built-in data types
- 2. How do you identify a value's type?
- 3. Numeric types: int, float, complex and bool
- Integers
- Floating-point numbers
- Complex numbers
- Boolean values
- 4. Text: str
- 5. Sequence types: list, tuple and range
- 6. Mapping type: dict
- 7. Set types: set and frozenset
- 8. Binary data: bytes, bytearray and memoryview
- 9. NoneType and truth values
- 10. Mutable and immutable objects
- 11. Choosing the right data type
- 12. Type conversion
- 13. Practical example: summarising an order
- 14. Exact type checks versus isinstance
- 15. Common mistakes
- Interview-ready answer
- Official references
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#
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.
| Type | Example | Mutability | Typical purpose |
|---|---|---|---|
| int | 42 | Immutable | Whole numbers |
| float | 3.5 | Immutable | Floating-point calculations |
| complex | 2+3j | Immutable | Complex arithmetic |
| bool | True | Immutable | Logical values |
| str | 'Python' | Immutable | Unicode text |
| list | [1, 2] | Mutable | Ordered collections |
| tuple | (1, 2) | Immutable | Fixed sequences of references |
| range | range(5) | Immutable | Arithmetic sequences of integers |
| dict | {'id': 1} | Mutable | Key-value associations |
| set | {1, 2} | Mutable | Unique hashable elements |
| frozenset | frozenset({1, 2}) | Immutable | Immutable sets |
| bytes | b'abc' | Immutable | Binary data |
| bytearray | bytearray(b'abc') | Mutable | Editable binary buffers |
| memoryview | memoryview(b'abc') | Depends on backing buffer | Buffer access without an ordinary data copy |
| NoneType | None | Immutable | Absence 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.
PYTHONvalues = [42, 3.5, 2+3j, True, 'Python', None] for value in values: print(type(value).__name__)
Output:
int
float
complex
bool
str
NoneTypeNo 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.
PYTHONprint(7 // 2, 7 / 2) print((2 + 3j).real, (2 + 3j).imag) print(isinstance(True, int))
Output:
3 3.5
2.0 3.0
TrueThe 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.
PYTHONtext = 'Python' print(text[0], text[-1]) print(text[1:4])
Output:
P n
ythIndex 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.
PYTHONitems = ['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.
PYTHONstock = {'pen': 4, 'book': 2} stock['pen'] += 1 print(stock['pen']) print(list(stock)) print(stock.get('bag', 0))
Output:
5
['pen', 'book']
0The 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.
PYTHONtags = {'python', 'sql', 'python'} print(sorted(tags)) print('python' in tags) print(frozenset({1, 2}) == {1, 2})
Output:
['python', 'sql']
True
TrueThe 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.
PYTHONraw = '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.
PYTHONprint(bool(0), bool([]), bool('0')) print(None is None)
Output:
False False True
TrueThe 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.
PYTHONa = [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#
| Requirement | Suitable starting type |
|---|---|
| Count completed tasks | int |
| Represent an approximate physical measurement | float |
| Represent a logical condition | bool |
| Store a person's name | str |
| Maintain a changing ordered collection | list |
| Represent a fixed coordinate pair | tuple |
| Iterate over consecutive integers | range |
| Look up records by unique identifiers | dict |
| Track distinct tags or visited nodes | set |
| Represent an immutable collection of unique elements | frozenset |
| Read or transmit encoded binary data | bytes |
| Edit an in-memory binary buffer | bytearray |
| Represent a missing optional result | None |
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.
PYTHONprint(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#
PYTHONorders = [{'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#
PYTHONprint(type(True) is bool) print(isinstance(True, int)) print(isinstance('abc', str))
Output:
True
True
TrueThe 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#
| Mistake | Better understanding |
|---|---|
| Treating {} as an empty set | Use set() |
| Treating tuples as deeply immutable | Referenced objects can be mutable |
| Assuming set iteration order is fixed | Sort comparable elements for deterministic display |
| Using a list as a dictionary key | Keys must be hashable |
| Confusing str and bytes | Use explicit encoding and decoding |
| Assuming bool('False') is False | A nonempty string is truthy |
| Using float for exact decimal money without a rounding policy | Consider integer minor units or Decimal |
| Assuming None and zero are equivalent | Handle 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#
- Python Standard Library — Built-in Types
- Python Language Reference — Data model
- Python Tutorial — Data Structures
- Python Standard Library — Built-in Functions
- Python Tutorial — Floating-Point Arithmetic: Issues and Limitations
- Python Standard Library — decimal
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.
References
- 1.Python Standard Library — Built-in Typesdocs.python.org
- 2.Python Language Reference — Data modeldocs.python.org
- 3.Python Tutorial — Data Structuresdocs.python.org
- 4.Python Standard Library — Built-in Functionsdocs.python.org
- 5.
- 6.Python Standard Library — decimaldocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design