Python Data Types

Learn about the different data types available in Python and how to use them.

Built-in Data Types

In programming, data type is an important concept. Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

Text Type

str

Numeric Types

int, float, complex

Sequence Types

list, tuple, range

Mapping Type

dict

Set Types

set, frozenset

Boolean Type

bool

Binary Types

bytes, bytearray, memoryview

None Type

NoneType

Getting the Data Type

You can get the data type of any object by using the type() function:

Example

x = 5
print(type(x))

Setting the Data Type

In Python, the data type is set when you assign a value to a variable:

Example

x = "Hello World"

Data Type: str

Example

x = 20

Data Type: int

Example

x = 20.5

Data Type: float

Example

x = 1j

Data Type: complex

Example

x = ["apple", "banana", "cherry"]

Data Type: list

Example

x = ("apple", "banana", "cherry")

Data Type: tuple

Example

x = range(6)

Data Type: range

Example

x = {"name" : "John", "age" : 36}

Data Type: dict

Example

x = {"apple", "banana", "cherry"}

Data Type: set

Example

x = frozenset({"apple", "banana", "cherry"})

Data Type: frozenset

Example

x = True

Data Type: bool

Example

x = b"Hello"

Data Type: bytes

Setting the Specific Data Type

If you want to specify the data type, you can use the following constructor functions:

Example

x = str("Hello World")

Data Type: str

Example

x = int(20)

Data Type: int

Example

x = float(20.5)

Data Type: float

Example

x = complex(1j)

Data Type: complex

Example

x = list(("apple", "banana", "cherry"))

Data Type: list

Example

x = tuple(("apple", "banana", "cherry"))

Data Type: tuple

Example

x = range(6)

Data Type: range

Example

x = dict(name="John", age=36)

Data Type: dict

Example

x = set(("apple", "banana", "cherry"))

Data Type: set

Example

x = frozenset(("apple", "banana", "cherry"))

Data Type: frozenset

Example

x = bool(5)

Data Type: bool

Example

x = bytes(5)

Data Type: bytes

Mutable vs Immutable

This is the most important distinction between the built-in types. Immutable objects cannot be changed after creation; mutable ones can.

ImmutableMutable
int, float, bool, complexlist
strdict
tuple, frozensetset
bytesbytearray
s = "hello"
# s[0] = "H"          # TypeError: strings are immutable
s = "H" + s[1:]       # make a NEW string instead
print(s)              # Hello

nums = [1, 2, 3]
nums[0] = 99          # lists are mutable
print(nums)           # [99, 2, 3]

Check a Type

x = 3.14
print(type(x))                 # <class 'float'>
print(isinstance(x, float))    # True
print(isinstance(x, (int, float)))   # True -> any of these

Prefer isinstance(x, int) over type(x) == intisinstance also accepts subclasses and a tuple of types.

Try It Yourself

Exercise 1: Print the type of True, 10, "10", and [10].

Show solution
for v in (True, 10, "10", [10]):
    print(type(v))
# bool, int, str, list

Exercise 2: Is a tuple mutable or immutable? Prove it in code.

Show solution
t = (1, 2, 3)
# t[0] = 9   # TypeError -> tuples are immutable
print("immutable")

Key Takeaways

  • Python has numeric, text, sequence, mapping, set, boolean, and binary types.
  • Immutable objects (str, tuple, int) cannot change in place; mutable ones (list, dict, set) can.
  • Use type() to inspect and isinstance() to test types.

📘 Real-World Deep Dive

Choosing the right built-in type (<code>set</code> vs <code>list</code>, <code>tuple</code> vs <code>namedtuple</code>, <code>int</code> vs <code>Decimal</code>) is the single biggest lever on both correctness and performance.

Real-Life Scenario

A de-duplication + aggregation pipeline on a million-row CSV — the right types turn a slow script into a 2-second one.

Real-Life Example

import csv
from collections import Counter, defaultdict
from decimal import Decimal

seen_ids: set[str] = set()
totals: defaultdict[str, Decimal] = defaultdict(lambda: Decimal("0"))

with open("orders.csv", newline="") as f:
    reader = csv.DictReader(f)
    for row in reader:
        if row["order_id"] in seen_ids:
            continue                    # set lookup ⇒ O(1)
        seen_ids.add(row["order_id"])
        totals[row["product"]] += Decimal(row["amount"])

top = Counter(totals).most_common(3)
print("Top 3 products by revenue:")
for product, amount in top:
    print(f"  {product}: {amount}")

Expected Output

Top 3 products by revenue:
  mug: 1823.40
  shirt: 970.00
  cap: 412.10

Common mistakes

  • Using a list for membership tests is O(n) — switch to set for membership, dict for lookup.
  • float cannot safely represent money — every finance check should use decimal.Decimal or store integer cents.
  • Mixing str IDs that look like ints ("0010") loses leading zeros; convert intentionally.

🚀 Performance & Best Practices

  • set lookups and dict lookups are amortised O(1); lists are O(n).
  • int arithmetic is ~50× faster than Decimal — store money as cents (e.g. int) when correctness allows.
  • Use dataclasses or typing.NamedTuple instead of free-form dicts in hot paths to make intent explicit.

🧪 Try It Yourself

  1. Benchmark the example above using list instead of set — record the slowdown.
  2. Convert amounts to integer cents and re-run — note the precision plus the speedup.
  3. Replace defaultdict(lambda: Decimal("0")) with a Counter after adjusting precision.

FAQ: Python Data Types

Common questions about this page.

What is Python Data Types?

Python Data Types is a Python Tutorial lesson that explains python data types in Python. Learn about the different data types available in Python and how to use them. Copy the samples and run them in the Python editor. It is written for beginners who want a clear definition and working examples.

Should I run python data types examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn python data types in this Python Tutorial Python lesson (Python Data Types).

How do I use python data types in Python?

To use python data types in Python, follow the examples on this StudyGrid page. Copy a snippet, run it in the browser, then Download and run it locally for better learning. Change the values and compare the output.

What is the syntax of python data types?

This Python Data Types tutorial shows python data types syntax with short Python examples. Use the code blocks in this lesson for the exact statements, then try them in your editor.

Python Data Types example for beginners

Yes. This page includes a beginner python data types example you can copy and run. It is designed for searches such as "python data types for beginners", "python data types example", and "how to use python data types".

What are common mistakes with python data types?

Common python data types mistakes include wrong syntax, mixing types, and skipping practice. Work through this Python Tutorial chapter in order, run every example, and check the output before moving on.

Why should I learn python data types?

Python Data Types is used in real Python work. Learning python data types helps you write clearer programs and continue the Python Tutorial tutorial on StudyGrid.

Is Python Data Types free to learn online?

Yes. You can learn python data types free on StudyGrid (studygrid.in). This chapter is part of the Python Tutorial path and includes examples, syntax, and next-step links.