Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 149 ยท Data Types

Data Types

Tour Python's built-in data types - numbers, strings, lists, tuples, dicts, sets and None - check them with type() and isinstance(), and learn about mutability.

Every value in Python has a type. The type decides what the value can do: you can add two numbers, make a string uppercase, or append to a list, but you can't make a number uppercase. Knowing the types and what they're for is the foundation for everything else you'll write.

This lesson is a map of the territory. You'll meet each built-in type briefly, learn to ask Python what type a value is with type() and isinstance(), and understand the most important difference between types: whether they're mutable (changeable) or immutable. The following lessons then explore the main types one by one.

The built-in types at a glance

Python ships with a small set of core types. You'll use the first group in almost every program:

Category Type Example Used for
Numbers int 42, -7, 1_000_000 whole numbers of any size
float 3.14, -0.5, 2e6 numbers with a fractional part
complex 2 + 3j complex numbers (math, engineering)
Text str "hello", 'ฮฉ' text of any length
Truth bool True, False yes/no answers
Nothing NoneType None "no value here"
Sequences list [1, 2, 3] ordered, changeable collections
tuple (48.85, 2.35) ordered, fixed collections
range range(10) sequences of numbers
Mappings dict {"name": "Ana", "age": 30} key โ†’ value lookups
Sets set {"red", "green"} unique items, fast membership tests
frozenset frozenset({1, 2}) an unchangeable set
Binary bytes, bytearray b"PNG" raw bytes from files and networks

You don't declare types. Python infers the type from how you write the value: quotes make a string, a decimal point makes a float, square brackets make a list.

Python One of each

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

type(value).__name__ gives the type's name as plain text, and !r shows each value the way you'd write it in code. Don't worry about the loop syntax yet; for Loops explains it.

Checking a type with type()

type() returns the type of any value. Printing it shows something like <class 'int'>: in Python, types are classes, and every value is an object of some class.

Python Asking for the type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

7, 7.0 and "7" look alike to a person but are three different types to Python. That's often the cause of bugs: data read from input() or a file is text even when it looks like a number.

Checking a type with isinstance()

When your code needs to decide what to do based on a type, prefer isinstance(value, type). It answers "is this value an instance of this type?" and accepts a tuple of types to check several at once:

Python isinstance()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line prints True because bool is a subclass of int: True behaves like 1 and False like 0 in arithmetic. That's why describe() checks bool before checking for numbers. isinstance() respects subclasses; type(x) == int doesn't. That's usually what you want, and it's the main reason isinstance() is preferred.

Tip: Much Python code doesn't check types at all. It just tries the operation and handles the error if it fails. This style is called duck typing: "if it walks like a duck and quacks like a duck, treat it as a duck." Check types when you truly need different behavior, not as a reflex.

Mutable and immutable types

This is the most important property of a type after what it represents. A mutable object can be changed in place after it's created. An immutable object can't: every "change" actually creates a new object.

  • Immutable: int, float, complex, bool, str, tuple, frozenset, bytes, None
  • Mutable: list, dict, set, bytearray, and most objects you create from your own classes

Strings are immutable, so string methods return new strings and leave the original alone. Lists are mutable, so list methods change the list itself:

Python Changing in place vs. creating new

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The try/except lets the program show the error and keep going. You'll learn it properly in Exceptions and try/except.

Why mutability matters

Remember from Variables and Names that names are labels on objects. When two names share a mutable object, a change through one name is visible through the other. With immutable objects that can't happen, because nothing can change them:

Python Shared objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

id() returns a number identifying an object while it exists. If id(x) == id(y), the names refer to the very same object; x is y asks the same question more directly.

Hashable types

Mutability also explains a rule you'll meet with dictionaries and sets: their keys and items must be hashable, which in practice means immutable. A string, number or tuple can be a dictionary key; a list can't, because changing it later would break the dictionary's lookups.

Python
locations = {(48.85, 2.35): "Paris"}   # a tuple key works
locations[[48.85, 2.35]] = "Paris"      # TypeError: unhashable type: 'list'

Choosing the right type

A few rules of thumb for picking a type:

  • Counting things? int. Measuring things? float. Money? Usually int cents or decimal.Decimal (see Numbers).
  • Text of any kind, including digits you won't calculate with (phone numbers, ZIP codes): str.
  • A collection that will grow or change: list.
  • A fixed group of related values, like a coordinate: tuple.
  • Looking things up by name or ID: dict.
  • Removing duplicates or testing membership fast: set.
  • "Not set yet" or "no result": None.
Python Types working together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice student_id is a string. If it were an int, the leading zeros would be lost: int("00417") is 417.

Converting between types

You can often turn a value of one type into another by calling the type like a function: int("42"), float(3), str(9.5), list("abc"), bool(0). Each conversion has its own rules and failure cases, which Type Conversion covers in detail.

Python
print(int("42") + 1)      # 43
print(str(42) + "1")      # '421'
print(list("abc"))        # ['a', 'b', 'c']
print(float("1e3"))       # 1000.0

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does type(3.0) return?

    The decimal point makes it a float, even though its value is a whole number.
  2. 2. Which of these types is mutable?

    Lists can be changed in place with methods like append(). Strings, tuples and ints are immutable.
  3. 3. What does isinstance(False, int) return?

    bool is a subclass of int, so every bool is also an int. That's why checks for bool should come before checks for int.
  4. 4. Why can't a list be used as a dictionary key?

    Keys must be hashable, which in practice means immutable. Numbers, strings and tuples of immutable values all work as keys.
  5. 5. Which type is best for a ZIP code such as 02134?

    Storing it as a number would drop the leading zero. Values you don't do math with are usually text.

Summary

  • Every value has a type, and the type decides what operations work on it.
  • Core types: int, float, complex, str, bool, None, list, tuple, range, dict, set, frozenset, bytes.
  • type(x) tells you the exact type; isinstance(x, T) also accepts subclasses and tuples of types, and is usually preferred.
  • bool is a subclass of int.
  • Immutable types (numbers, strings, tuples) can't change in place; mutable types (lists, dicts, sets) can, and every name that shares them sees the change.
  • Dictionary keys and set items must be hashable (immutable).

Next: Numbers, a closer look at integers, floats, rounding and precise decimal math.