بخشی از مجموعه

Several example codes

~2 دقیقه مطالعه • بروزرسانی ۹ مهر ۱۴۰۴

Program Overview

This Python program calculates and displays the memory usage of multiple data items.
It uses the sys.getsizeof() function to measure memory in bytes.


Python Code:


import sys

# Define sample data items
items = [
    42,                      # Integer
    3.14,                    # Float
    "Hello Shahin عزیز دلم", # String
    [1, 2, 3],               # List
    {"a": 1, "b": 2},        # Dictionary
]

# Display memory usage for each item
print("--- Memory Usage of Each Item ---")
for item in items:
    size = sys.getsizeof(item)
    print(f"{type(item).__name__}: {size} bytes")

Sample Output:


--- Memory Usage of Each Item ---
int: 28 bytes  
float: 24 bytes  
str: 78 bytes  
list: 80 bytes  
dict: 232 bytes

Step-by-Step Explanation:

- A list of sample items is defined, including integers, floats, strings, lists, and dictionaries
- The sys.getsizeof() function is used to measure memory usage
- The type and memory size of each item are printed in a structured format


نوشته و پژوهش شده توسط دکتر شاهین صیامی