Python Data Types

Python Tutorial › Basics › Data Types

Python Data Types

BeginnerLesson 9 of 4711 min read8 runnable examples

Every value in Python has a type, and the type decides what you can do with it: you can add two numbers, make a string upper case, or append to a list. This lesson is a tour of the built-in types you will use every day.

In this lesson
  • The built-in data types at a glance
  • Check a value’s type with type() and isinstance()
  • Mutable vs immutable types
  • Choose the right collection for the job

Built-in data types at a glance

CategoryTypeExampleNotes
Textstr"hello"Immutable sequence of characters
Numbersint42, -7Whole numbers of any size
float3.14, 1e-3Decimal numbers
complex2 + 3jUsed in maths and engineering
BooleanboolTrue, FalseResult of comparisons
NothingNoneTypeNone“No value yet”
Sequenceslist[1, 2, 3]Ordered, changeable
tuple(1, 2, 3)Ordered, unchangeable
rangerange(5)Sequence of numbers, created on demand
Mappingdict{"id": 7}Key-value pairs
Setsset{1, 2, 3}Unique items, no order
Binarybytesb"abc"Raw bytes from files and networks

Check the type of a value

type() returns the exact type of a value:

Python
values = [42, 3.14, 2 + 3j, "py", True, None, [1], (1,), {1}, {"a": 1}, range(3), b"x"]for v in values:    print(repr(v).ljust(10), type(v).__name__)
Output
42         int
3.14       float
(2+3j)     complex
'py'       str
True       bool
None       NoneType
[1]        list
(1,)       tuple
{1}        set
{'a': 1}   dict
range(0, 3) range
b'x'       bytes

Use isinstance() in real code. It also accepts a tuple of types and understands subclasses:

Python
price = 99.5print(isinstance(price, float))print(isinstance(price, (int, float)))print(isinstance(True, int))     # bool is a subclass of int
Output
True
True
True

Numbers

Python
big = 2 ** 100          # ints never overflowprint(big)print(7 / 2, 7 // 2)    # / always gives a float, // rounds downprint(0.1 + 0.2)        # floats are approximate
Output
1267650600228229401496703205376
3.5 3
0.30000000000000004
Note

0.1 + 0.2 is not exactly 0.3 because floats are stored in binary. Use round() for display, or the decimal module for money. The Numbers & Math lesson goes deeper.

Strings

A string is text in single, double or triple quotes. Strings support indexing, slicing and many methods.

Python
course = "Python Tutorial"print(course.upper())print(course[0], course[-1])print(len(course))print("Tut" in course)
Output
PYTHON TUTORIAL
P l
15
True

Booleans and None

True and False come from comparisons and are used by if and while. None means “no value”.

Python
is_logged_in = 5 > 3print(is_logged_in, type(is_logged_in)) result = Noneprint(result is None)
Output
True <class 'bool'>
True

Every value is either “truthy” or “falsy”. Empty values and zero are falsy:

Python
for v in [0, 1, "", "a", [], [0], None]:    print(repr(v).ljust(5), bool(v))
Output
0     False
1     True
''    False
'a'   True
[]    False
[0]   True
None  False

Collections: list, tuple, set, dict

Python
skills = ["python", "sql", "python"]          # list: ordered, duplicates allowedpoint = (12.5, 77.3)                          # tuple: fixed recordunique_skills = set(skills)                   # set: duplicates removeduser = {"name": "Asha", "role": "tester"}     # dict: look up by key print(skills)print(point[0])print(len(unique_skills))print(user["role"])
Output
['python', 'sql', 'python']
12.5
2
tester
NeedUse
An ordered list of items you will changelist
A fixed group of values, such as coordinatestuple
Unique items, or fast “is it in here?” checksset
Look up a value by a keydict

Mutable vs immutable

A mutable object can change after it is created; an immutable one cannot.

  • Immutable: int, float, bool, str, tuple, frozenset, bytes.
  • Mutable: list, dict, set, bytearray.
Python
name = "python"name.upper()           # returns a NEW stringprint(name)            # the original is unchanged name[0] = "P"          # strings cannot be changed in place
Output
python
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    name[0] = "P"          # strings cannot be changed in place
    ~~~~^^^
TypeError: 'str' object does not support item assignment
Watch out

Because lists and dicts are mutable, passing one to a function lets that function change your data. Strings and numbers are safe from that.

Check your understanding

Predict the output

print(type(7 / 7).__name__, type(7 // 7).__name__, type("7").__name__)

Quick quiz

1. What is the type of (5,)?

2. Which type removes duplicates automatically?

3. Which of these is immutable?

4. What does bool([]) return?

Exercise: describe each value

Loop over the list and print each value with its type name and whether it is truthy.

Input
[0, 2.5, "", "hi", None, [3]]
Expected output
0      int       False
2.5    float     True
''     str       False
'hi'   str       True
None   NoneType  False
[3]    list      True
Hint 1

type(v).__name__ gives the type name as a string.

Program Practice

Python data types FAQ

How many data types are there in Python?

Python has about a dozen commonly used built-in types: int, float, complex, bool, str, list, tuple, range, dict, set, frozenset, bytes and NoneType. You can also create your own with classes.

How do I check the data type of a variable?

Use type(x) to see the type, or isinstance(x, int) to test it.

What is the difference between mutable and immutable types?

Mutable objects such as lists and dicts can be changed in place. Immutable objects such as strings, numbers and tuples cannot; operations on them return new objects.

Is a string a sequence in Python?

Yes. A string is an immutable sequence of characters, so it supports indexing, slicing, len() and in.