TExcelTAD
Home › Python › Python Data Types

Python Data Types

Every value in Python has a type. The type decides what you can do with the value: you can divide numbers, uppercase strings and append to lists, but not the other way round. Python sets the type automatically based on the value you write.

Built-in types

Category Types Example
Text str "hello"
Numbers int, float, complex 7, 2.5, 1+2j
Sequences list, tuple, range [1, 2], (1, 2), range(5)
Mapping dict {"a": 1}
Sets set, frozenset {1, 2}
Boolean bool True, False
Binary bytes, bytearray, memoryview b"hi"
Nothing NoneType None

Finding the type with type()

python · try it yourself
values = ["text", 42, 3.5, 2 + 3j, [1, 2], (1, 2), range(3),
          {"k": "v"}, {1, 2}, True, b"abc", None]

for v in values:
    print(type(v).__name__)
str
int
float
complex
list
tuple
range
dict
set
bool
bytes
NoneType

type(v) returns the class object; .__name__ gives just its name, which is tidier to print.

Checking a type with isinstance()

When your code needs to test a type, prefer isinstance(). It also accepts a tuple of types:

python · try it yourself
def describe(value):
    if isinstance(value, (int, float)):
        return "a number"
    if isinstance(value, str):
        return "some text"
    return "something else"

print(describe(10))
print(describe(2.5))
print(describe("hi"))
print(describe([1]))
a number
a number
some text
something else

Mutable vs immutable

A crucial property of a type is whether its values can be changed in place.

Immutable (can't change) Mutable (can change)
int, float, bool, str, tuple, frozenset, bytes list, dict, set, bytearray

"Changing" an immutable value really creates a new one:

python · try it yourself
word = "cat"
upper = word.upper()
print(word, upper)      # the original string is untouched

pets = ["cat"]
pets.append("dog")      # the list itself is modified
print(pets)
cat CAT
['cat', 'dog']

Setting a specific type

The type comes from the value you write, but you can also build a value using the type's constructor:

python · try it yourself
print(str(12))
print(int("12") + 1)
print(float(3))
print(list("abc"))
print(tuple([1, 2]))
print(dict(name="Lan", age=30))
print(bool(0), bool(5))
12
13
3.0
['a', 'b', 'c']
(1, 2)
{'name': 'Lan', 'age': 30}
False True

This is called casting and has its own lesson.

None

None is Python's way of saying "no value". It is the only value of type NoneType, and functions that don't return anything return None. Compare with it using is:

python · try it yourself
result = None
print(result is None)
True

Note: Each of these types gets its own lesson later — this page is the map.

Test yourself

What is the type of (1, 2, 3)?

  1. list
  2. set
  3. tuple
  4. dict

Which of these types is mutable?

  1. str
  2. tuple
  3. int
  4. list

What does type(None).__name__ give?

  1. None
  2. null
  3. NoneType
  4. void