Using the delete () of () list block, one can remove a specified item from a list based on its numerical value in the list, but there is no individual block that removes an item (or multiple items) which contains a specified string from a list. This tutorial will show how to remove an item from a list based on the string stored within the item.

Project Situations

There could be a number of purposes why one would need to remove an item from a list based on its value (or string). The following are possible situations:

  • A list contains of items found, and the items are in random order based on when they were discovered; later, one item is given away, and the list must remove that specified item based on its name from the list.
  • A grocery list being broken down as items are bought

Programming

Archive.png
The subject of this article or section has changed dramatically and requires updating. Please keep in mind that some of the information or images may not be accurate or relevant to the current version of Scratch, the Scratch website, or the article subject. (January 2019)
Specifically: Can use item # block

The following script can be used to program this. For this script, assume the following:

  • "item#" is a variable used to iterate through the list until finding the desired item.
  • The list's name is "gems".
  • The item which is desired to be removed is the string "ruby".
Note Note: this first method only removes the first instance of the specified string. The next method removes all instances of the specified string.
set [item# v] to (1) //so the process begins with the first item
if <[gems v] contains [ruby]> then //if it does not, then the list cannot delete the item, and the script will not run further
repeat until <(item (item#) of [gems v]) = [ruby]> //it will stop once it reaches the first item that is "ruby"
change [item# v] by (1) //moves to the next item in the list to check if it is a "ruby"
end
delete (item#) of [gems v]
end

This second method removes all items that are the specified string instead of just the first:

set [item# v] to (1) //so the process begins at item 1 of "gems"
if <[gems v] contains [ruby]> then //if the list at all contains "ruby"
repeat until < (item#) > (length of [gems v])> //repeat until iterated through the entire list
if <(item (item#) of [gems v]) = [ruby]> then //if the current item is the specified string
delete (item#) of [gems v] //then remove that item
else
change [item# v] by (1) //move to the next item
end