DEV Community

VALENTINE ACHIENG
VALENTINE ACHIENG

Posted on

# 🐍 Python Data Types: The Ultimate Beginner's Guide (with Examples)

Understanding data types is one of the most important parts of learning Python. Whether you're building a calculator, a web app, or analyzing data, everything you do involves data β€” and that data always has a type.

In this article, we’ll dive deep into Python's data types, show real code examples with outputs, explain why each type matters, and even explore how to use arrays in Python using array and NumPy.


🧐 What Are Data Types in Python?

In Python, a data type tells the interpreter what kind of value a variable holds β€” is it a number? a list? a sentence?

Python is dynamically typed, meaning you don’t have to declare data types. It figures them out when the code runs.


πŸ“† 1. Numeric Types

Numeric types represent numbers, and Python supports three main numeric types:

πŸ”’ int (Integer)

Used to store whole numbers (positive or negative) without decimal points.

x = 42
print(x)           # 42
print(type(x))     # <class 'int'>
Enter fullscreen mode Exit fullscreen mode

Integers can be very large in Python:

big = 12345678901234567890
print(big)          # 12345678901234567890
Enter fullscreen mode Exit fullscreen mode

πŸ”’ float (Floating-point)

Represents numbers with decimal points. These are useful for measurements, scores, percentages, etc.

pi = 3.14159
print(pi)           # 3.14159
print(type(pi))     # <class 'float'>
Enter fullscreen mode Exit fullscreen mode

Python also supports scientific notation:

sci = 1.2e3
print(sci)          # 1200.0
Enter fullscreen mode Exit fullscreen mode

Note: Floats can have rounding errors due to binary representation.


πŸ”’ complex (Complex numbers)

Stores numbers with a real and imaginary part. Mostly used in scientific computing.

z = 2 + 3j
print(z)            # (2+3j)
print(z.real)       # 2.0
print(z.imag)       # 3.0
Enter fullscreen mode Exit fullscreen mode

πŸ“ 2. Text Type

str (String)

A string is a sequence of characters. Strings are used to represent text data.

name = "Vall"
message = 'Hello, world!'
print(name)         # Vall
print(type(name))   # <class 'str'>
Enter fullscreen mode Exit fullscreen mode

Strings support many operations:

print(name.upper())     # VALL
print("Python"[0])      # P
print("Vall" in name)   # True
Enter fullscreen mode Exit fullscreen mode

f-strings are used to embed variables in strings:

age = 21
print(f"My name is {name} and I am {age} years old.")
# My name is Vall and I am 21 years old.
Enter fullscreen mode Exit fullscreen mode

πŸ“š 3. Sequence Types

list

A list is an ordered collection of items. It is mutable, meaning it can be changed after creation.

fruits = ["apple", "banana", "cherry"]
print(fruits[0])        # apple
fruits.append("orange")
print(fruits)           # ['apple', 'banana', 'cherry', 'orange']
Enter fullscreen mode Exit fullscreen mode

tuple

A tuple is similar to a list but immutable β€” once created, it can't be changed.

point = (10, 20)
print(point)            # (10, 20)
Enter fullscreen mode Exit fullscreen mode

Attempting to modify it causes an error:

# point[0] = 15  # TypeError: 'tuple' object does not support item assignment
Enter fullscreen mode Exit fullscreen mode

range

Used to generate a sequence of numbers, often in loops.

r = range(5)
print(list(r))          # [0, 1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

🧽 4. Set Types

set

A set is an unordered, mutable collection of unique elements. That means no duplicates are allowed, and the order is not guaranteed.

colors = {"red", "green", "blue", "red"}
print(colors)  # {'green', 'red', 'blue'}
Enter fullscreen mode Exit fullscreen mode

You can add or remove elements:

colors.add("yellow")
print(colors)

colors.remove("green")
print(colors)
Enter fullscreen mode Exit fullscreen mode

Mathematical set operations are supported:

a = {1, 2, 3}
b = {3, 4, 5}
print(a & b)  # intersection: {3}
print(a | b)  # union: {1, 2, 3, 4, 5}
print(a - b)  # difference: {1, 2}
Enter fullscreen mode Exit fullscreen mode

Sets are useful for checking membership and removing duplicates from a list:

nums = [1, 2, 2, 3, 4, 4, 5]
unique_nums = set(nums)
print(unique_nums)  # {1, 2, 3, 4, 5}
Enter fullscreen mode Exit fullscreen mode

frozenset

A frozenset is like a set, but immutable β€” once created, you can't add or remove elements. This makes it hashable and usable as a dictionary key or element in another set.

fs = frozenset([1, 2, 3, 2])
print(fs)  # frozenset({1, 2, 3})
Enter fullscreen mode Exit fullscreen mode

You can perform the same operations as with a set (except mutation):

fs1 = frozenset([1, 2, 3])
fs2 = frozenset([3, 4, 5])
print(fs1 & fs2)  # intersection: frozenset({3})
Enter fullscreen mode Exit fullscreen mode

But this will raise an error:

# fs.add(6)  # AttributeError: 'frozenset' object has no attribute 'add'
Enter fullscreen mode Exit fullscreen mode

Use frozenset when you need a constant set of values that should not be changed.


πŸ—˜οΈ 5. Mapping Type

dict

A dictionary stores key-value pairs.

student = {
    "name": "Vall",
    "age": 21,
    "course": "CS"
}
print(student["name"])   # Vall
student["age"] = 22
print(student)
# {'name': 'Vall', 'age': 22, 'course': 'CS'}
Enter fullscreen mode Exit fullscreen mode

✨ 6. Boolean Type

bool

Boolean values represent True or False. They are commonly used in conditions.

is_active = True
print(is_active)        # True
print(type(is_active))  # <class 'bool'>
Enter fullscreen mode Exit fullscreen mode

Expressions that return booleans:

print(10 > 5)           # True
print(10 < 3)           # False
Enter fullscreen mode Exit fullscreen mode

❌ 7. None Type

NoneType

Represents the absence of a value.

x = None
print(x)                # None
print(type(x))          # <class 'NoneType'>
Enter fullscreen mode Exit fullscreen mode

Often used for default values or empty returns.


πŸ”„ Type Checking and Conversion

x = 100
print(type(x))              # <class 'int'>
print(isinstance(x, int))   # True

str_x = str(x)
print(str_x)                # '100'
print(type(str_x))          # <class 'str'>
Enter fullscreen mode Exit fullscreen mode

♻️ Mutable vs Immutable

Data Type Mutable?
int, float, str, tuple, bool, None ❌ No
list, dict, set βœ… Yes

πŸ“Œ Arrays in Python

Python doesn’t have a native array type like Java or C++, but we can use:

1. array module (basic)

import array
nums = array.array('i', [1, 2, 3, 4])
print(nums)                # array('i', [1, 2, 3, 4])
print(nums[0])             # 1
Enter fullscreen mode Exit fullscreen mode

'i' indicates integers. 'f' for float, 'd' for double.


2. NumPy Arrays (powerful & preferred for data science)

import numpy as np
arr = np.array([10, 20, 30])
print(arr)                 # [10 20 30]
print(arr.dtype)           # int64 (platform dependent)
print(arr + 5)             # [15 25 35]
Enter fullscreen mode Exit fullscreen mode

NumPy arrays are faster, more efficient, and used in machine learning, AI, and data science.

Install with:

pip install numpy
Enter fullscreen mode Exit fullscreen mode

🧠 Mini Challenge

a = [1, 2, 3]
b = a
b.append(4)
print(a)      # ?
Enter fullscreen mode Exit fullscreen mode

Answer: [1, 2, 3, 4] because both a and b point to the same list (mutable).


βœ… Final Thoughts

Data types are the foundation of Python programming. Mastering them helps you:

  • Store and process data effectively
  • Avoid bugs
  • Build real applications

From int to dict, from list to NumPy arrays β€” Python gives you tools to handle any kind of data.

Happy coding πŸπŸš€!

Top comments (0)