Item # of () in ()
(item # of [] in [ v])
Category List
Type Reporter
Introduced in 3.0
The correct title of this article is Item # of () in (). The Scratch Wiki uses this different title because of technical restrictions.

Item Number of () in () is a list block and a reporter block. This block reports the index in a list where an item first appears. If an item appears more than once, it reports the index of the first occurrence of that item. If the item is not in a list, it reports 0. It is one of the only reporter blocks that can be inserted into a boolean input. This block was added in Scratch 3.0.

Example

when gf clicked
delete all of [list v]
add [a] to [list v]
add [b] to [list v]
add [c] to [list v]
add [b] to [list v]
say (item # of [c] in [list v]) //says 3 since c is the third item in the list
say (item # of [b] in [list v]) //says 2 since the first occurrence of b in the list is in the second position
say (item #  of [d] in [list v]) //says 0 since d is not in the list

Workaround

This can instead be accomplished by looking at each item in a list in order and seeing if any of them equal the item being searched for.

define search list for (search term)
set [counter v] to [1] //the position in the list we are currently looking at
set [result v] to [0] //if we find the item we are looking for, we will store its position here
repeat until <<(counter) > (length of [list v])> or <not <(result) = [0]>>> //exit the loop if we either have found the item we are looking for or we have looked at every item in the list and not found it
  if <(item (counter) of [list v]) = (search term)> then
    set [result v] to (counter) //if the item at the position we are currently looking at is equal to what we are looking for, then store the current position as the result
  else
    change [counter v] by [1] //otherwise, look at the next position
  end
end

Related Suggestion

Some Scratchers want an operators block that reports the appearance of a string in another. Such a block would look like this:[citation needed]

(letter # of () in ():: operators)

However, it can be worked around by this code:

define get index of (letter) in (string)
set [result v] to (0)
set [counter v] to (0)
delete all of [characters v]
repeat (length of (string))
change [counter v] by (1)
add (letter (counter) of (string)) to [characters v]
end
set [counter v] to (0)
repeat until <<(counter) > (length of (string))> or <(letter (counter) of (string)) = (letter)>>
change [counter v] by (1)
if <(letter (counter) of (string)) = (letter)> then
set [result v] to (counter)
end
end
Note Note: Only works if length of letter is 1.

See Also

Cookies help us deliver our services. By using our services, you agree to our use of cookies.