Lesson 13 +10 XP

Data Types

Data Types

Everything in Python is an object with a type. Setting a variable defines its type automatically.

Built-in types

CategoryTypes
Textstr
Numbersint, float, complex
Sequencelist, tuple, range
Mappingdict
Setset, frozenset
Booleanbool
Binarybytes, bytearray, memoryview
NoneNoneType

How to set a type

Just assign a value of that kind:

x = "Hello"        # str
x = 20             # int
x = 20.5           # float
x = 1j             # complex
x = ["a", "b"]     # list
x = ("a", "b")     # tuple
x = range(6)       # range
x = {"name": "Ada"}# dict
x = {"a", "b"}     # set
x = True           # bool
x = None           # NoneType

Specify a type with constructors

You can also force a type using the type name:

x = str("Hello")
x = int(20)
x = list(("a", "b"))
x = dict(name="Ada", age=36)

Check a type

Use type() to ask Python what a value is.

print(type(20))       # <class 'int'>
print(type([1, 2]))   # <class 'list'>

Mutable vs immutable

  • Mutable types can change after creation: list, set, dict.
  • Immutable types cannot change: str, tuple, int, bool, frozenset.

TL;DR

  • The value decides the type; type() reveals it.
  • Core types: str, int, float, list, tuple, dict, set, bool.
  • Use constructors like str(), list() to force a type.
  • Lists, sets, dicts are mutable; strings and tuples are immutable.