Removing Items From Lists

Description

We can remove an item from a list in Sage using the .remove() method. The method is applied to a list, and removes the specified item.

Sage Cell

Code

A = [ 2, 3, 5, 7, 11 ]
A.remove(5)
print A

Options

Del and Pop

We can remove an item from a list by its index using the commands del or .pop(). .pop() is different in that it returns the value removed, as well as the fact that the default index to be popped is -1. This means if no argument is passed to .pop(), the las item in the list will be popped. Note that del and .pop() are applied to the array in different ways.

Code

A = [ 2, 3, 5, 7, 11 ]
del A[2]
print A
A = [ 2, 3, 5, 7, 11 ]
b = A.pop(2)
print A
print b

Deleting a Range of Items

You can delete a range of indices using del as well. For a list s, the command del s[i:j] will delete all items from indices i to j, not including j. You can also use del s[i:j:k] to remove items from i to j with step k (for instance, if k = 1 every item is removed, if k = 2 every other item is removed and so on).

Code

A = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ]
del A[3:6]
print A
A = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ]
del A[2:8:2]
print A

Tags

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.

Attribute

Permalink:

Author:

Date: 25 Mar 2019 13:47

Submitted by: Zane Corbiere

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