The built-in predicate bagof(+Template, +Goal, -Bag) is used to collect a list Bag of all the items Template that satisfy some goal Goal. Example: assume

likes(mary, pizza).
likes(marco, pizza).
likes(Human, pizza) :- italian(Human).
?- bagof(Person, likes(Person, pizza), Bag).
Person = _G180
Bag = [mary, marco, marco]

Notice that Bag contains the item marco twice, because there are two ways to prove that marco likes pizza - the fact and via the rule. bagof fails if Goal has no solutions.

See also setof, and, for differences between bagof and findall, see findall.