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

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 only two reporter blocks that can be inserted into a boolean input, the other one being the Item () of () (block) block.

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 item # of (search term) in list
set [counter v] to (0)
set [result v] to (0)
repeat (length of [list v])
  change [counter v] by (1)
  if <(item (counter) of [list v])=(search term)> then
    set [result v] to (counter)
    stop [this script v]
  end
end

or

define item # of (string) in list
set [result v] to [0]
if <[list v] contains (string)?> then
    repeat until <(item (result) of [list v]) = (string)> 
        change [result v] by (1)
    end
end

In a Boolean Input

This block can be inserted into a boolean input, despite being a reporter block. The only other block with this special property is Item () of ().

All integers are casted to true except for 0, so this block is effectively true when the given item exists in the list. It is rather useless in a boolean input as the <[ v] contains []?> block exists and can do the same thing.

Related Suggestion

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

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

However, it can be worked around by this code:

define letter # of (letter) in (string)
set [counter v] to (0)
set [result v] to (0)
repeat (length of (string))
  change [counter v] by (1)
  if <(letter (counter) of (string))=(letter)> then
    set [result v] to (counter)
    stop [this script v]
  end
end
Note Note: Only works if the length of letter is 1.

See Also

References

  1. codeman1044. (2019-05-18). "letter # of () in () [title]" topic:351646
Cookies help us deliver our services. By using our services, you agree to our use of cookies.