indusai.co

Data types

Every value in Python has a type, and the type decides what you can do with it. You can add two numbers, but you cannot add a number to a piece of text without converting one of them first.

The built in types

CategoryTypesExample
Textstr"hello"
Numericint, float, complex42, 3.14, 2+3j
Sequencelist, tuple, range[1, 2], (1, 2), range(5)
Mappingdict{"a": 1}
Setset, frozenset{1, 2, 3}
BooleanboolTrue, False
Binarybytes, bytearrayb"data"
NoneNoneTypeNone

Checking a type

type() returns the type of any value.

python
print(type(42))
print(type(3.14))
print(type("text"))
print(type([1, 2, 3]))
print(type(True))
print(type(None))

isinstance() is the better choice inside if statements because it also accepts subclasses:

python
value = 10
if isinstance(value, int):
    print("value is an integer")

Python decides the type for you

You do not write the type. Python infers it from the literal you wrote.

python
a = 5          # int
b = 5.0        # float
c = "5"        # str
d = [5]        # list with one int
e = (5,)       # tuple with one int (the comma matters)
f = {5}        # set
g = {"n": 5}   # dict

for item in (a, b, c, d, e, f, g):
    print(repr(item), "is a", type(item).__name__)

Setting a specific type

When you need a particular type you call the type's constructor function:

python
x = str(5)       # "5"
y = int("7")     # 7
z = float(3)     # 3.0
w = list("abc")  # ["a", "b", "c"]
print(x, y, z, w)

This is called casting and has its own lesson next.

Mutable and immutable

Some types can be changed in place after creation (mutable) and some cannot (immutable). This distinction matters more than it first appears, especially when passing values into functions.

  • Immutable: int, float, str, tuple, bool, frozenset
  • Mutable: list, dict, set
python
numbers = [1, 2, 3]
numbers.append(4)      # the same list, modified
print(numbers)

text = "abc"
text = text + "d"      # a brand new string; the old one is untouched
print(text)

None

None represents "no value". Functions that do not explicitly return anything return None, and it is the usual placeholder for "not set yet".

python
result = None
if result is None:
    print("Nothing here yet")

Always compare with is None, never == None.

Practice

  1. Create one value of each of these types: int, float, str, list, dict, bool. Print each with its type.
  2. Predict the type of 10 / 2 and of 10 // 2, then check with type().