What are the different forms of data storage in Python?
In Python, there are several ways to store data, such as:
- Variables: They can be used to store individual data values. For example, variables can be used to store an integer, decimal, string, etc.
x = 10
y = 3.14
name = "John"
- List: A list is an ordered, mutable data type that can store multiple data values. Elements in a list can be of different data types.
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
mixed_list = [1, "apple", True, 3.14]
- A tuple is an ordered, immutable data type that can store multiple values, with elements in a tuple able to be of different data types.
person = ("John", 25, "male")
point = (2, 3)
- Dictionary: A dictionary is an unordered data type composed of key-value pairs. Each key-value pair represents a data item, and you can retrieve the corresponding value based on the key.
student = {"name": "John", "age": 25, "gender": "male"}
- Set: A set is an unordered, non-repeating data type that can be used to store multiple data values. It can perform set operations such as finding intersections, unions, and differences.
fruits = {"apple", "banana", "orange"}
numbers = {1, 2, 3, 4, 5}
- File: Data can be stored in files for persistent storage and retrieval between different program runs.
# 写入文件
with open("data.txt", "w") as file:
file.write("Hello, World!")
# 读取文件
with open("data.txt", "r") as file:
data = file.read()
print(data)
These are commonly used data storage formats in Python, and you can choose the appropriate one based on your needs.