# Python List Examples: Advance python examples

Now welcome readers, Lets take a look at what python list is? then we move forward on their complex examples.

## What is Python List?

A Python list is a versatile & fundamental data structure that is used to store collections of items. Lists in Python are ordered, mutable, and can contain elements of different data types, including numbers, strings, & even other lists. Lists are defined by enclosing their elements in square brackets `[ ]`, separated by commas. Let’s look at some of the best and very advance example on python list.

### Examples NO. 1

In this example we demonstrates the use of Python lists in the context of analyzing sensor data from a measurement system. Let’s say we have collected temperature readings from multiple sensors over time and want to perform some data analysis:

# Simulated temperature sensor data
sensor1_data = [25.4, 25.8, 26.2, 25.6, 25.9]
sensor2_data = [26.0, 25.5, 25.7, 25.8, 25.6]
sensor3_data = [25.9, 26.1, 25.7, 26.2, 25.8]

# Combine data from multiple sensors into a list of lists
sensor_data = [sensor1_data, sensor2_data, sensor3_data]

# Calculate the average temperature for each time step
average_temperatures = []
for i in range(len(sensor1_data)):
time_step_values = [sensor[i] for sensor in sensor_data]
average_temp = sum(time_step_values) / len(sensor_data)
average_temperatures.append(average_temp)

# Find the maximum and minimum temperatures across all sensors
max_temperature = max([max(sensor) for sensor in sensor_data])
min_temperature = min([min(sensor) for sensor in sensor_data])

# Calculate the standard deviation of temperatures at each time step
import statistics
std_deviations = [statistics.stdev([sensor[i] for sensor in sensor_data]) for i in range(len(sensor1_data))]

# Print the results
print(“Average Temperatures:”, average_temperatures)
print(“Max Temperature:”, max_temperature)
print(“Min Temperature:”, min_temperature)
print(“Standard Deviations:”, std_deviations)

In this engineering-level example:

1. We have data from three temperature sensors (`sensor1_data`, `sensor2_data`, and `sensor3_data`), each represented as a list of temperature readings.
2. We combine the data from all sensors into a single list of lists (`sensor_data`) for ease of analysis.
3. We calculate the average temperature for each time step by taking the mean of the corresponding readings from all sensors.
4. We find the maximum and minimum temperatures recorded across all sensors.
5. We calculate the standard deviation of temperatures at each time step to assess the data’s variability.

In this example we demonstrates how Python lists can be used to handle real-world engineering data and perform various calculations and analyses on the data, making it a valuable tool for engineers and scientists working with data from sensors and measurements.

### Examples NO. 2

In this example we show the use of Python lists and libraries to analyze and visualize data from multiple sensors in a 2D plane. In this example, we’ll simulate the data from a sensor network and create a heatmap to visualize the spatial distribution of temperature readings:

import numpy as np
import matplotlib.pyplot as plt

# Simulated temperature sensor data for a 5×5 grid
grid_size = 5
sensor_data = np.random.uniform(20, 30, size=(grid_size, grid_size))

# Create a list of lists to represent the sensor grid
sensor_grid = sensor_data.tolist()

# Calculate statistics on the sensor data
average_temp = np.mean(sensor_data)
max_temp = np.max(sensor_data)
min_temp = np.min(sensor_data)

# Visualize the temperature distribution as a heatmap
plt.figure(figsize=(8, 6))
plt.imshow(sensor_data, cmap=’YlOrRd’, interpolation=’nearest’, origin=’upper’, extent=[0, grid_size, 0, grid_size])
plt.colorbar(label=’Temperature (°C)’)
plt.title(‘Temperature Distribution in Sensor Grid’)
plt.xlabel(‘X-coordinate’)
plt.ylabel(‘Y-coordinate’)
plt.xticks(np.arange(0, grid_size + 1, 1))
plt.yticks(np.arange(0, grid_size + 1, 1))
plt.grid(color=’white’, linestyle=’–‘, linewidth=0.5)
plt.show()

# Print the results
print(“Average Temperature:”, average_temp)
print(“Max Temperature:”, max_temp)
print(“Min Temperature:”, min_temp)

In this more complex engineering-level example:

1. We simulate temperature sensor data for a 5×5 grid using NumPy to generate random temperature readings within a specified range.
2. We create a list of lists (`sensor_grid`) to represent the temperature readings in the 2D sensor grid.
3. We calculate statistics on the sensor data, including the average, maximum, and minimum temperatures across the grid.
4. We use Matplotlib to visualize the temperature distribution as a heatmap, which provides a spatial representation of the sensor data.
5. The resulting heatmap displays temperature variations across the grid, making it easier to identify hotspots or anomalies in the sensor network.

In this example we showcases the use of Python lists, NumPy for numerical operations, and Matplotlib for data visualization, demonstrating a more complex engineering application involving data analysis and visualization.

### Example NO.3

In this example we use of Python lists and libraries to analyze and visualize real-world sensor data over time. In this example, we’ll work with time-series sensor data and perform advanced data analysis and visualization:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Simulate time-series temperature sensor data for three sensors
num_time_steps = 100
sensor1_data = np.sin(np.linspace(0, 4 * np.pi, num_time_steps)) * 10 + np.random.normal(0, 1, num_time_steps)
sensor2_data = np.cos(np.linspace(0, 4 * np.pi, num_time_steps)) * 8 + np.random.normal(0, 1, num_time_steps)
sensor3_data = np.random.normal(25, 1, num_time_steps)

# Create a time index for the data
time_index = pd.date_range(start=”2023-01-01″, periods=num_time_steps, freq=”H”)

# Store the sensor data in a DataFrame
sensor_df = pd.DataFrame({‘Time’: time_index, ‘Sensor1’: sensor1_data, ‘Sensor2’: sensor2_data, ‘Sensor3’: sensor3_data})

# Calculate rolling statistics (e.g., rolling mean) for each sensor
window_size = 10
rolling_mean_sensor1 = sensor_df[‘Sensor1’].rolling(window=window_size).mean()
rolling_std_sensor2 = sensor_df[‘Sensor2’].rolling(window=window_size).std()

# Visualize the sensor data and rolling statistics
plt.figure(figsize=(12, 6))
plt.plot(sensor_df[‘Time’], sensor_df[‘Sensor1′], label=’Sensor 1’, alpha=0.7)
plt.plot(sensor_df[‘Time’], sensor_df[‘Sensor2′], label=’Sensor 2’, alpha=0.7)
plt.plot(sensor_df[‘Time’], sensor_df[‘Sensor3′], label=’Sensor 3’, alpha=0.7)
plt.plot(sensor_df[‘Time’], rolling_mean_sensor1, label=’Rolling Mean (Sensor 1)’, linestyle=’–‘, color=’red’)
plt.plot(sensor_df[‘Time’], rolling_std_sensor2, label=’Rolling Std (Sensor 2)’, linestyle=’–‘, color=’blue’)
plt.xlabel(‘Time’)
plt.ylabel(‘Temperature (°C)’)
plt.title(‘Sensor Data and Rolling Statistics’)
plt.legend()
plt.grid()
plt.show()

# Perform advanced analysis such as anomaly detection or correlation analysis
# (These analyses can be complex and involve additional libraries)

# Save the sensor data to a CSV file for further analysis
sensor_df.to_csv(‘sensor_data.csv’, index=False)

In this more complex engineering-level example:

1. We simulate time-series temperature sensor data for three sensors, including sinusoidal and random data patterns.
2. We create a time index using `pandas` to represent the timestamp for each data point.
3. The sensor data is stored in a `pandas` DataFrame, allowing for efficient data manipulation and analysis.
4. We calculate rolling statistics (rolling mean and standard deviation) for Sensor 1 and Sensor 2, demonstrating time-series data analysis techniques.
5. We visualize the sensor data and rolling statistics using `matplotlib`, providing insights into the sensor behavior over time.
6. The code also hints at the possibility of performing more advanced analyses, such as anomaly detection or correlation analysis, depending on the specific engineering application.
7. Finally, we save the sensor data to a CSV file for further analysis or archival purposes.

We showcases a more complex engineering application involving time-series data, statistical analysis, and data visualization, demonstrating the versatility of Python lists and related libraries for advanced engineering tasks.