Chapters
Python114 chapters

BasicsChapter 9 of 114

Data Types

The built-in types you will actually use, and how to ask what something is.

Asking what something is

Every value has a type. type() tells you which:

Python
print(type(42))
print(type(3.14))
print(type("hello"))
print(type(True))

Output

<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>

The ones worth knowing now

TypeWhat it holdsExample
intwhole numbers, any size42
floatnumbers with a decimal point3.14
strtext"hello"
boolTrue or FalseTrue
listan ordered run of items you can change[1, 2, 3]
tuplean ordered run you cannot change(1, 2)
dictkeys pointing at values{"a": 1}
setunordered, no duplicates{1, 2}
NoneTypethe absence of a valueNone
Python
print(type([1, 2, 3]))
print(type((1, 2)))
print(type({"a": 1}))
print(type({1, 2}))
print(type(None))

Output

<class 'list'>
<class 'tuple'>
<class 'dict'>
<class 'set'>
<class 'NoneType'>

None is not zero and not empty

None means "no value here". It is its own type, and the way to test for it is is None:

Python
result = None
print(result is None)
print(result == 0)
print(result == "")

Output

True
False
False

Mutable or not

The division that matters most in practice: some objects can be changed in place, and some cannot.

Python
numbers = [1, 2, 3]
numbers[0] = 99
print(numbers)

text = "abc"
print(text.upper())
print(text)

Output

[99, 2, 3]
ABC
abc

The list changed. The string did not — upper() handed back a new string and left the original alone. Strings, numbers and tuples are immutable; lists, dicts and sets are not.

Checking a type properly

Use isinstance() rather than comparing type() results, because it also accepts subclasses:

Python
value = 10
print(isinstance(value, int))
print(isinstance(value, (str, float)))

Output

True
False

Test yourself

2 questions

Which of these can be changed in place?

Show the answer

list — Strings, numbers and tuples are immutable. A string method hands back a new string and leaves the original alone.

How should you check whether a value is None?

Show the answer

value is None — 0 and "" are falsy but are perfectly good values. Only 'is None' asks the question you mean.

Next chapter

Numbers

Integers, floats, the two kinds of division, and why 0.1 + 0.2 misbehaves.