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
| Category | Types | Example |
|---|---|---|
| Text | str | "hello" |
| Numeric | int, float, complex | 42, 3.14, 2+3j |
| Sequence | list, tuple, range | [1, 2], (1, 2), range(5) |
| Mapping | dict | {"a": 1} |
| Set | set, frozenset | {1, 2, 3} |
| Boolean | bool | True, False |
| Binary | bytes, bytearray | b"data" |
| None | NoneType | None |
Checking a type
type() returns the type of any value.
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:
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.
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:
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
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".
result = None
if result is None:
print("Nothing here yet")Always compare with is None, never == None.
Practice
- Create one value of each of these types:
int,float,str,list,dict,bool. Print each with its type. - Predict the type of
10 / 2and of10 // 2, then check withtype().
