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:
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
| Type | What it holds | Example |
|---|---|---|
int | whole numbers, any size | 42 |
float | numbers with a decimal point | 3.14 |
str | text | "hello" |
bool | True or False | True |
list | an ordered run of items you can change | [1, 2, 3] |
tuple | an ordered run you cannot change | (1, 2) |
dict | keys pointing at values | {"a": 1} |
set | unordered, no duplicates | {1, 2} |
NoneType | the absence of a value | None |
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:
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.
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:
value = 10
print(isinstance(value, int))
print(isinstance(value, (str, float)))Output
True False
Test yourself
2 questionsWhich 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.
Numbers
Integers, floats, the two kinds of division, and why 0.1 + 0.2 misbehaves.