Introduction

Understanding Python data types is essential for writing efficient and bug-free code. Python offers various built-in data types that help developers store and manipulate data effectively.

This guide explores all the fundamental data types in Python with examples to help you master them quickly.

What Are Data Types in Python?

Data types define the kind of values a variable can store. Python is dynamically typed, meaning you don’t need to declare a variable’s data type explicitly; Python determines it automatically.

1. Numeric Data Types

Python supports three primary numeric types:

a. Integer (int)

Used for whole numbers, both positive and negative.

x = 10
print(type(x))  # Output: <class 'int'>

b. Float (float)

Used for decimal (floating-point) numbers.

y = 10.5
print(type(y))  # Output: <class 'float'>

c. Complex (complex)

Used for complex numbers with real and imaginary parts.

z = 3 + 5j
print(type(z))  # Output: <class 'complex'>

2. Sequence Data Types

These types store ordered collections of elements.

a. String (str)

A sequence of characters enclosed in single or double quotes.

text = "Hello, Python!"
print(type(text))  # Output: <class 'str'>

b. List (list)

An ordered, mutable collection of elements.

my_list = [1, 2, 3, "Python", 4.5]
print(type(my_list))  # Output: <class 'list'>

c. Tuple (tuple)

An ordered, immutable collection of elements.

my_tuple = (1, 2, 3, "Python")
print(type(my_tuple))  # Output: <class 'tuple'>

3. Set Data Types

Sets are unordered collections of unique elements.

a. Set (set)

my_set = {1, 2, 3, 4, 4, 5}
print(type(my_set))  # Output: <class 'set'>

b. Frozen Set (frozenset)

An immutable version of a set.

my_frozenset = frozenset([1, 2, 3, 3, 4])
print(type(my_frozenset))  
# Output: <class 'frozenset'>

4. Mapping Data Types

a. Dictionary (dict)

A collection of key-value pairs.

my_dict = {"name": "Python", "version": 3.10}
print(type(my_dict))  # Output: <class 'dict'>

5. Boolean Data Type

Booleans represent True or False values.

is_python_fun = True
print(type(is_python_fun))  # Output: <class 'bool'>

6. Binary Data Types

Used for handling binary data.

a. Bytes (bytes)

Immutable binary data.

b = b"Hello"
print(type(b))  # Output: <class 'bytes'>

b. Bytearray (bytearray)

Mutable binary data.

ba = bytearray(5)
print(type(ba))  # Output: <class 'bytearray'>

c. Memoryview (memoryview)

Creates a view of binary data.

mv = memoryview(bytes(5))
print(type(mv))  # Output: <class 'memoryview'>

Conclusion

Python provides a rich set of data types to handle various kinds of data effectively. Understanding these types allows for better programming practices and efficient code management.