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 – using a list comprehension


Let's see how list comprehensions work by comparing them to a for loop that performs a similar operation. Enter the following code in a text file or an input cell in a worksheet:

list1 = [' a  ', '    b   ', 'c   ']

list1_stripped = []
for s in list1:
    list1_stripped.append(s.strip())
print(list1_stripped)

list1_stripped_2 = [s.strip() for s in list1]
print(list1_stripped_2)

list2 = []
for val in srange(0.0, 10.0, 1.0):
    if val % 2 == 0:
        list2.append(numerical_approx(val**2, digits=3))
print(list2)

list3 = [numerical_approx(val**2, digits=3) for val in 
    srange(0.0, 10.0, 1.0) if val % 2 == 0]
print(list3)

Run the example. You should get:

What just happened?

This example demonstrated how a list comprehension can be used in place of a for loop to create a list. In the first part of the example, we defined a list of strings, each of which contained whitespace before and/or after the character. First, we defined an empty list and...