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 – accessing items in a list


Evaluate the following code:

list1 = ['a', 'b', 'c', 'd', 'e']
print("A list of characters: " + str(list1))

# Getting elements with indices and slices
print("list1[0] = " + str(list1[0]))
print("list1[1:4] = " + str(list1[1:4]))
print("list1[1:] = " + str(list1[1:]))
print("list1[:4] = " + str(list1[:4]))
print("list1[-1] = " + str(list1[-1]))
print("list1[-3:] = " + str(list1[-3:]))

The results should look like this:

What just happened?

The items in a list can be accessed using an integer value, which is known as an index. The index is placed in a square bracket like this:

sage: list1[0]
'a'

The index of the first item is zero, the index of the next element is one, and so on. It's also possible to select elements from the end of the list instead of the beginning. The last element is -1, the second-to-last is -2, etc.

Multiple elements can be selected at once using slice notation. The colon is the slice operator. The slice starts at the index corresponding...