Iterating Through Lists


Due to the nature of an index of a list, we can use a for loop to easily iterate through its contents. Remember that we call a specific list item using the name of the list and the index in brackets, like so: A[1].

Sage Cell


A = [ 2, 3, 5, 7, 11 ]
for i in range (0, len(A)):
    print A[i]


Iterating Backwards

Using negative indices, we can iterate through a list backwards. Note that negative indices start at -1, not , and for loops themselves can not iterate backwards, so we start the range at 1 and end it at the length of the list, inclusively. This requires us to set the range for list A as (1, len(A) + 1), as the second value in the range is exclusive.


A = [ 2, 3, 5, 7, 11 ]
for i in range (1, len(A) + 1):
    print A[-i]


Primary Tags:

Secondary Tags:

A list of possible tags can be found at The WeBWorK Open Problem Library. For linear algebra tags see the Curated Courses Project.

Related Cells

Any related cells go here. Provide a link to the page containing the information about the cell.




Date: 25 Mar 2019 12:03

Submitted by: Zane Corbiere

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License