The difference between tuple and array

Both tuple and array are data structures used in Python to store multiple values, but there are some differences in their implementation and use.

  1. Tuples are immutable while arrays are mutable. That is, once a tuple is created, its content cannot be modified, while an array can be added, deleted, changed, and so on.

  2. The elements in a tuple can be any type of object, including objects of different types; while arrays usually require all elements to have the same data type in order to maintain efficient underlying storage.

  3. Tuples support indexing and slicing operations, similar to strings, but arrays have more methods and functions, such as adding/removing elements, sorting, searching, etc.

  4. In Python, tuples are usually used to represent immutable, ordered data collections, such as when a function returns multiple values, accessing dictionary key-value pairs, formatting strings, etc.; while arrays are usually used to store a large number of the same type data, such as scientific calculations or numerical operations.

Here is a simple example showing some basic operations on tuples and arrays:


pythonCopy code

# Create a tuple
my_tuple = (1, 2, 3)

# Create an array
import array
my_array = array.array('i', [1, 2, 3])

# Access elements in the tuple and array
print(my_tuple [0]) # Output 1
print(my_array[1]) # Output 2

# Attempt to modify elements in tuples and arrays
my_tuple[0] = 4 # This line of code will throw TypeError because tuples are immutable
my_array[1] = 5 # Change the second element in the array to 5

# Add a new element at the end of the array
my_array.append(4)

# Get the number of elements in the array
print(len(my_array)) # Output 4

# Convert array to list
my_list = my_array.tolist()



In the above example, we created a tuple and array of three integers and demonstrated how to access and modify their elements. It should be noted that trying to modify elements in a tuple will result in a TypeError exception, while adding or removing elements to an array is fine. Additionally, we showed how to get the number of elements in an array and convert it to a list.

f6439aa0d2b7c064fbe4910de6c23814.jpeg

2b857c7af8e54e22d6cbba3eec8608d8.jpeg

Guess you like

Origin blog.csdn.net/zhaomengsen/article/details/131354135