2.3. Built-in Types and Functions#

Hide code cell source

import sys
from pathlib import Path

current = Path.cwd()
for parent in [current, *current.parents]:
    if (parent / '_config.yml').exists():
        project_root = parent  # ← Add project root, not chapters
        break
else:
    project_root = Path.cwd().parent.parent

sys.path.insert(0, str(project_root))

from shared import thinkpython, diagram, jupyturtle, download, structshape

# Register as top-level modules so direct imports work in subsequent cells
sys.modules['thinkpython'] = thinkpython
sys.modules['diagram'] = diagram
sys.modules['jupyturtle'] = jupyturtle
sys.modules['download'] = download
sys.modules['structshape'] = structshape

Python has standard types built into the interpreter. The principal built-in types are: numerics, sequences, mappings, classes, instances, and exceptions. The commonly used data types can be organized as Fig. 2.1.

This chapter builds upon the variables and data types introduced earlier, providing deeper coverage of Python’s type system and advanced operations.

2.3.1. About Types#

Python is dynamically typed, which means you don’t have to declare the data type when creating a variable. The interpreter will figure it out at run time. For example, the x below will receive proper types without user intervention.

x = 10
x = "hello"
x = [1, 2, 3, ]
x[0] = "M S&T"

A kind of value is called a type. Actually, every value has a type – or we sometimes say it “belongs to” a type. Python provides a function called type() that tells you the type of any value.

a = type(1)
b = type(2.0)
c = type(3/2)
d = type('Hello, World!')
e = type('126')       ### note this is a string, not a number

print(a, b, c, d, e, sep='\n')
<class 'int'>
<class 'float'>
<class 'float'>
<class 'str'>
<class 'str'>

type and the built-in function isinstance() work similarly, except isinstance() allows you to check the type you assume and returns True or False.

print(isinstance(1, int))
print(isinstance('126', str))
True
True

2.3.2. Common Built-in Types#

Python has standard types built into the interpreter. The principal built-in types are: numerics, sequences, mappings, classes, instances, and exceptions. The commonly used data types can be organized as table below.

In the Python standard library, they are grouped into 8 categories:

Group

No.

Category

Types

Remarks

Sample Use Case

Literals

1

Numeric

int, float, complex

Numbers for mathematical operations

Counts, indices, ages, prices, measurements

2

Text sequence

str

Text and character data

Names, messages, file paths

3

Boolean

bool

Logical values (True/False)

Flags, conditions, toggle states

4

Null

NoneType

Represents absence of value

Absence of value, default state

Collections

5

Sequence

list, tuple, range

Ordered collections of items

Shopping cart items, student grades, coordinates, RGB colors

6

Binary

bytes, bytearray, memoryview

Binary data and memory manipulation

Image data, encrypted content

7

Set

set, frozenset

Unordered collections of unique items

Removing duplicates, membership testing

8

Mapping

dict

Key-value pairs

User profiles, configuration settings

../../_images/python-data-types-2.png

Fig. 2.1 Python built-in data types #

2.3.3. Type Hierarchy#

The standard type hierarchy in the Python Language Reference lists 8 different built-in data types with a slightly different categorization:

No.

Category

Type(s)

Remarks

1

Null

NoneType

None, represents absence of value

2

NotImplemented

NotImplementedType

NotImplemented, a built-in constant indicating that an operation is not implemented for a particular type combination

3

Ellipsis

Ellipsis

..., a placeholder, explicitly signals intentional incompleteness

4

Numeric

integers (int and bool), float, complex

Numbers for mathematical operations and Boolean (True/False)

5

Sequence

str, tuple, bytes

immutable; ordered , indexed, and slicible collections of items; support slicing

list, bytearray

mutable; ordered, indexed, and slicible collections of items

6

Set

set, frozenset

Unordered collections of unique items; set is mutable and frozenset is not

7

Mapping

dict

Key-value pairs

8

Callable

User-defined functions

Instance methods

Generator functions

Coroutine functions

Asynchronous generator functions

Built-in functions

Built-in methods

Classes

Class Instances

2.3.4. Type Checking#

The built-in function type() returns the data type of the object; in this case, variables.

num1 = 10                   ### integer
num2 = 10.1                 ### floating-point number
greeting = "hello, world"   ### text/string
fruits = ['Apple', 'Banana', 'Cherry']      ### lists are enclosed with square brackets

print(type(num1))
print(type(num2))
print(type(greeting))
print(type(fruits))
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>

2.3.5. Type Conversion#

Type conversion is the general process of converting a value from one data type to another. There are two ways of type conversion to change type:

  • Type Casting (explicit conversion) is performed by the programmer (e.g., using int("42")) using the type constructors.

  • Type Coercion (implicit conversion) is performed automatically by the Python interpreter (e.g., 3 + 4.5 results in 7.5, where the integer 3 is coerced to a float to match the other operand).

2.3.5.1. Type Constructors#

Core Python types that are also constructor functions include:

Function

Converts To

Example

Explanation

int()

Integer

int("10") 10

Converts string “10” to integer 10

float()

Floating-point number

float("3.14") 3.14

Converts string “3.14” to floating-point 3.14

str()

String

str(25) "25"

Converts integer 25 to string “25”

bool()

Boolean (True/False)

bool(0) False, bool(5) True

0 converts to False, non-zero values convert to True

list()

List

list("abc") ['a','b','c']

Converts string into list of individual characters

tuple()

Tuple

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

Converts list to immutable tuple

set()

Set

set([1,1,2]) {1,2}

Converts list to set, removing duplicate values

As an example of type casting, let’s cast an integer to a float.

num = 1
print(num)
print(type(num))

num = float(num)
print(num)
print(type(num))
1
<class 'int'>
1.0
<class 'float'>

Type coercion is performed automatically by the Python interpreter at runtime. The Python interpreter decides the data type.

### type coercion

a = 7             # int
b = 3.0           # float
c = a + b         # Python automatically converts 'a' to a float (7.0) before addition
print(c)          # Output: 10.0
print(type(c))    # Output: <class 'float'>
10.0
<class 'float'>

Examples of type casting vs type coercion:

### type casting
num = 5
print("num's type:\t", type(num))
print("num's new type:\t", type(str(num)))  ### casting (explicit conversion) by programmer

### type coercion
x = 3               ### integer
y = 0.14            ### float
print(f"{x} + {y} is {x+y} and has the type: {type(x + y)}")        
                    ### int + float = float done automatically by Python interpreter
                    ### coercion (implicit conversion)  
num's type:	 <class 'int'>
num's new type:	 <class 'str'>
3 + 0.14 is 3.14 and has the type: <class 'float'>
### Exercise: Type Conversion
### Print the data type of variable 'num' after the addition
### The result should be as the cell below
### Your code begins here

num = "100.1"
num = float(num) + 1.0


### Your code ends here

Hide code cell source

print(type(num))
<class 'float'>

2.3.6. Type Hinting#

Type hinting, also called type annotation, lets you write the expected type next to a variable name. A type hint is a note for humans and development tools; Python does not enforce it by itself when the program runs.

At this point, focus on the basic idea:

age: int = 20
name: str = "Alice"
height: float = 5.9
is_active: bool = True

The annotation after the colon says what kind of value the variable is expected to hold. Later, when we define our own functions, we will use the same notation for function parameters and return values:

def add(a: int, b: int) -> int:
    return a + b

For now, remember two rules:

  • type hints improve readability and help tools catch mistakes early;

  • type hints do not convert values or stop the program at runtime.

num: int = 10               ### type hinting for integer
name: str = "Alice"         ### type hinting for string
is_active: bool = True      ### type hinting for boolean
height: float = 5.9         ### type hinting for float