Ordered Iteration#
List#
Lists in Python are ordered collections, meaning that the items have a defined order that will not change.
This characteristic is essential when the sequence of elements matters, as in many engineering computations.
# Example: Calculating moving averages in signal processing
import numpy as np
# Signal: A list of voltage measurements over time
voltages = [1.2, 1.5, 1.8, 2.0, 2.1, 2.0, 1.8, 1.5, 1.3]
# Calculate the moving average using a window size of 3
window_size = 3
moving_averages = np.convolve(voltages, np.ones(window_size)/window_size, mode='valid')
print("Moving averages:", moving_averages)
Moving averages: [1.5 1.76666667 1.96666667 2.03333333 1.96666667 1.76666667
1.53333333]
The order of elements in the βvoltagesβ list is crucial for correctly computing the moving averages.
An unordered collection would not provide meaningful results in this context.
Dictionaries#
Since Python 3.7 dictionaries are guaranteed to maintain the insertion order of their elements.
# Dictionaries maintain insertion order as of Python 3.7
# Example: Storing and processing time-series data in the order of acquisition
# Time-stamped sensor data (time: sensor value)
sensor_data = {
'2024-02-01 10:00:00': 45.2,
'2024-02-01 10:01:00': 46.0,
'2024-02-01 10:02:00': 45.5,
'2024-02-01 10:03:00': 46.1
}
# Processing data in the order it was acquired is essential for time-series analysis
timestamps = list(sensor_data.keys())
values = list(sensor_data.values())
# Compute the rate of change between consecutive measurements
rate_of_change = [values[i+1] - values[i] for i in range(len(values)-1)]
print("Rate of change:", rate_of_change)
Rate of change: [0.7999999999999972, -0.5, 0.6000000000000014]
In this example, the ordered nature of dictionaries allows for predictable iteration over time-stamped data, which is crucial for accurate analysis and engineering computations.