Book Image

Sage Beginner's Guide

By : Craig Finch
1 (1)
Book Image

Sage Beginner's Guide

1 (1)
By: Craig Finch

Overview of this book

Table of Contents (17 chapters)
Sage Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – iterating over lists


Let's say you have some data stored in a list, and you want to print the data in a particular format. We will use three variations of the for loop to display the data.

time_values = [0.0, 1.5, 2.6, 3.1]
sensor_voltage = [0.0, -0.10134, -0.27, -0.39]

print("Iterating over a single list:")
for value in sensor_voltage:
    print(str(value) + " V")

print("Iterating over multiple lists:")
for time, value in zip(time_values, sensor_voltage):
    print(str(time) + " sec    " + str(value) + " V")
    
print("Iterating with an index variable:")
for i in range(len(sensor_voltage)):
    print(str(time_values[i]) + " sec    " + 
        str(sensor_voltage[i]) + " V")

The output should be:

What just happened?

We started by creating two lists: one to hold time values, and one to hold the measured value at each time point. In the first for loop, we iterated over the data list and printed each value. We iterated over the list with the syntax:

for loop_variable in list_name...