Reading history

Python Data Types: int, float, str, bool, list and dict

7 min read 0 views

Every built-in Python data type in one place: numbers, text, True/False, None and collections, plus type(), isinstance() and type conversion.

Every value in Python has a data type. The type decides what the value can do: you can divide numbers, make text uppercase, and add items to a list, but not the other way round. Python sets the type for you from the value you write.

In this lesson you will learn

  • The built-in data types and what each one is for
  • How to check a type with type() and isinstance()
  • Why 0.1 + 0.2 is not exactly 0.3
  • Which values count as true and false
  • The difference between mutable and immutable types
  • How to convert a value from one type to another

Python’s Built-in Data Types

Python groups its built-in types by what they hold.

CategoryTypeExampleUse it for
Numbersint42Whole numbers: counts, ages, roll numbers
float3.5Decimals: prices, weights, averages
complex2 + 3jEngineering and maths with imaginary numbers
Textstr"Dhaka"Names, messages, any text
True/falseboolTrueYes/no answers and conditions
NothingNoneTypeNone“No value yet” or “not found”
Sequenceslist[1, 2]Ordered items you will change
tuple(1, 2)Ordered items that stay fixed
rangerange(3)A run of numbers for loops
Mappingdict{"a": 1}Look up a value by its key
Setsset, frozenset{1, 2}Unique items, fast membership tests
Binarybytes, bytearrayb"hi"Raw data from files and networks

A single student record can use almost every type at once. The program below stores one field of each kind, then prints the type Python picked for it.

student = {
    "roll": 17,
    "cgpa": 3.82,
    "impedance": 4 - 2j,
    "name": "Tasnim",
    "has_scholarship": False,
    "phone": None,
    "marks": [78, 91],
    "birth_date": (2008, 3, 14),
    "class_days": range(1, 6),
    "address": {"city": "Khulna"},
    "clubs": {"debate", "robotics"},
    "photo_header": b"\x89PNG",
}

for field, value in student.items():
    print(f"{field:<16}{type(value).__name__}")

Output

roll            int
cgpa            float
impedance       complex
name            str
has_scholarship bool
phone           NoneType
marks           list
birth_date      tuple
class_days      range
address         dict
clubs           set
photo_header    bytes

The whole record is itself a dict, a collection of "field": value pairs. The f-string pads each field name to 16 characters so the types line up in a column. Each of these types gets its own lesson later in the course. (The impedance field is only there to show a complex number; you will rarely need one outside engineering.)

Numbers: int and float

An int has no size limit in Python. A float stores decimals in binary, which is fast but slightly inexact for some values.

population = 23_000_000      # underscores make big numbers readable
huge = 2 ** 100
print(population)
print(huge)

print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))

Output

23000000
1267650600228229401496703205376
0.30000000000000004
0.3

Underscores in 23_000_000 are only for your eyes; Python ignores them. 2 ** 100 is a 31-digit number, and Python handles it without overflow, unlike an int in C.

The result 0.30000000000000004 is not a Python bug. A computer keeps floats in base 2, and in base 2 the value one-tenth never ends; it repeats forever, so the computer keeps the nearest value that fits in 64 bits. That tiny gap shows up when you add such numbers. C, Java and JavaScript give the same answer. Use round() when displaying results, and use the decimal module when every paisa matters, as in accounting.

Checking a Type: type() and isinstance()

type(x) tells you the exact type. isinstance(x, T) answers yes or no, and also accepts a tuple of types to check several at once.

print(isinstance(5, int))
print(isinstance(5.0, int))
print(isinstance(True, int))   # bool is a kind of int
print(isinstance("5", (int, float)))

Output

True
False
True
False

isinstance(True, int) is True because bool is built on top of int: True behaves like 1 and False like 0. In real programs, prefer isinstance() over comparing type() results, because it also accepts related types.

Truthy and Falsy Values

Any value can be used in an if condition. Python treats “empty” or “zero” values as false and everything else as true. The bool() function shows which is which.

for value in [0, 7, "", "hi", [], [0], None, 0.0]:
    print(repr(value), "->", bool(value))

Output

0 -> False
7 -> True
'' -> False
'hi' -> True
[] -> False
[0] -> True
None -> False
0.0 -> False

The falsy values are 0, 0.0, empty text "", empty collections ([], (), {}, set()), None and False. Note that [0] is true: the list is not empty, even though its only item is zero. This lets you write if orders: instead of if len(orders) > 0:.

Mutable and Immutable Types

A mutable value can change after it is created. An immutable value cannot; any “change” builds a new value instead.

marks = [70, 80]
marks.append(90)          # lists can change
print(marks)

city = "dhaka"
upper_city = city.upper() # strings cannot change; this makes a new one
print(city, upper_city)

point = (3, 4)
try:
    point[0] = 10
except TypeError as err:
    print("Error:", err)

Output

[70, 80, 90]
dhaka DHAKA
Error: 'tuple' object does not support item assignment
Immutable (cannot change)Mutable (can change)
int, float, complex, bool, str, tuple, frozenset, bytes, Nonelist, dict, set, bytearray

This matters in two places. First, only immutable values can be dictionary keys or set items. Second, when two variables point to one mutable object, a change through one name shows up in the other, as you saw in the Variables lesson.

Converting Between Types

Each type name also works as a function that converts a value to that type.

print(int("250") + 50)
print(float("3.75"))
print(str(99) + " taka")
print(list("abc"))
print(tuple([1, 2, 3]))
print(set([1, 1, 2, 3, 3]))
print(int(9.99))

Output

300
3.75
99 taka
['a', 'b', 'c']
(1, 2, 3)
{1, 2, 3}
9
  • int("250") and float("3.75") turn text into numbers, which you need for anything a user types.
  • set(...) removes duplicates, a common one-line trick.
  • int(9.99) gives 9. It cuts off the decimals; it does not round. Use round(9.99) for 10.
  • int("9.5") or int("abc") raises a ValueError because the text is not a whole number.

Common Mistakes

  1. Comparing floats with ==. 0.1 + 0.2 == 0.3 is False. Use math.isclose(a, b) instead.
  2. Doing maths on text. "5" + 3 raises a TypeError. Convert first with int("5").
  3. Expecting int() to round. It always cuts toward zero.
  4. Writing {} for an empty set. {} is an empty dictionary. Use set().
  5. Using type(x) == int everywhere. It rejects related types; isinstance(x, int) is usually what you mean.

Practice Exercises

Exercise 1. Without running it, name the type of each value: 7, 7.0, "7", [7], (7,), {7}.

Show answer

int, float, str, list, tuple, set. The comma in (7,) is what makes it a tuple; (7) is just the number 7.

Exercise 2. Which of these print True? bool(" "), bool(0), bool([[]]), bool(None)

Show answer

bool(" ") and bool([[]]). A string with a space is not empty, and a list holding an empty list still has one item.

Exercise 3. prices = ["120", "80", "45"] holds text. Print their total as a number.

Show answer
prices = ["120", "80", "45"]
print(sum(int(p) for p in prices))   # 245

Exercise 4. Remove the duplicates from [3, 1, 3, 2, 1] and print the result as a sorted list.

Show answer
print(sorted(set([3, 1, 3, 2, 1])))   # [1, 2, 3]

Frequently Asked Questions

How many data types does Python have?

The core built-in types are int, float, complex, str, bool, NoneType, list, tuple, range, dict, set, frozenset, bytes and bytearray. Libraries and your own classes can add many more.

Does Python have a char type like C?

No. A single character is just a string of length 1, such as "a".

What is the difference between None and 0?

0 is a number. None means there is no value at all. Both are falsy, but None + 1 is an error while 0 + 1 is 1.

Why is a string immutable?

Immutable strings are safe to share between variables and can be used as dictionary keys. Methods like upper() return a new string instead of changing the old one.

Summary

  • Python sets each value’s type automatically; type() shows it.
  • Main types: int, float, str, bool, None, list, tuple, dict, set.
  • Floats are approximate; round for display and use math.isclose() to compare.
  • Zero, empty and None values are falsy; everything else is truthy.
  • Lists, dicts and sets are mutable; numbers, strings and tuples are not.
  • Convert with int(), float(), str(), list(), set().
Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *