Python Data Types

Python is a dynamically typed language, which means that the type of a variable is determined at runtime. Python comes with a wide range of built-in data types that help you work with different kinds of data efficiently. Understanding Python data types is essential for writing effective Python programs. Let's explore the different data types available in Python.

Built-in Data Types in Python

Python supports the following built-in data types:

Numeric Data Types

Numeric data types are used to store numerical values. Python supports three different types of numeric data:

Code Example


# Numeric data types
int_num = 10
float_num = 20.5
complex_num = 2 + 3j

print("Integer:", int_num)
print("Float:", float_num)
print("Complex:", complex_num)
            

Output

Integer: 10 Float: 20.5 Complex: (2+3j)

Sequence Data Types

Sequence types are used to store multiple items in a single variable. Python has three main sequence types:

Code Example


# Sequence data types
string_val = "Python"
list_val = [1, 2, 3, "Hello"]
tuple_val = (10, 20, 30, "World")

print("String:", string_val)
print("List:", list_val)
print("Tuple:", tuple_val)
            

Output

String: Python
List: [1, 2, 3, 'Hello'] Tuple: (10, 20, 30, 'World')

Mapping Data Type

The Dictionary (dict) is a collection of key-value pairs. Dictionaries are unordered, mutable, and indexed by keys, which can be any immutable type. Dictionaries are defined using curly braces (e.g., {"name": "John", "age": 25}).

Code Example


# Dictionary data type
student = {
    "name": "John",
    "age": 21,
    "courses": ["Math", "Science"]
}

print("Student Name:", student["name"])
print("Student Age:", student["age"])
print("Courses:", student["courses"])
            

Output

Student Name: John Student Age: 21 Courses: ['Math', 'Science']

Set Data Types

A Set is an unordered collection of unique items. Sets are mutable and do not allow duplicate values. They are defined using curly braces (e.g., {1, 2, 3}). Python also has frozenset, which is an immutable version of set.

Code Example


# Set data type
num_set = {1, 2, 3, 3, 4}
frozen_set = frozenset([1, 2, 3])

print("Set:", num_set)
print("Frozenset:", frozen_set)
            

Output

Set: {1, 2, 3, 4} Frozenset: frozenset({1, 2, 3})

Boolean Data Type

The Boolean (bool) data type represents one of two values: True or False. Booleans are often used in conditional statements.

Code Example


# Boolean data type
is_active = True
is_expired = False

print("Is Active:", is_active)
print("Is Expired:", is_expired)
            

Output

Is Active: True Is Expired: False

Understanding Python's data types is essential for writing efficient and effective programs. By utilizing the correct data type, you can optimize memory usage and improve the performance of your Python applications. Knowing the characteristics and limitations of each data type allows you to select the most appropriate type for your specific use case.