How to randomly select more then one items from a list?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By praveenyadav1602

Assume I have the following list of 52 cards:

    Cards = ['club1' , 'club2',  'club3',  'club4', 'club5', 'club6','club7','club8','club9','club10' ,club11,'club12','club13','heart1', 'heart2', 'heart3',  'heart4', 'heart5', 'heart6', 'heart7',  
'heart8', 'heart9','heart10',  'heart11', 'heart12','heart13',  'diamond1',   'diamond2',    'diamond3', 'diamond4', 'diamond5',  'diamond6', 'diamond7',    'diamond8',diamond9','diamond10','diamond11',  'diamond12', 'diamond13', 'spades1',        'spades2', 'spades3', 'spades4', 'spades5', 'spades6', 'spades7', 'spades8', 'spades9',
 'spades10',   'spades11', 'spades12',  'spades13', ]

I want to select 13 items randomly from list at once,
What is the simplest way to retrieve items at random from this list?

:bust_in_silhouette: Reply From: Zylann

A simple way is to shuffle the cards, and pick the first 13.

var picked_cards = cards.slice(0, 13)

If you want to keep the order in which cards were before, you can copy the array beforehand and truncate the copy to 13:

var picked_cards = cards.duplicate()

Another way is to randomly pick 13 cards, while also checking we haven’t picked twice the same one, but it may be better suited for very large arrays (not like a card game):

var picked_cards = []
while len(picked_cards) < 13:
	var card = cards[randi() % len(cards)]
	if not picked_cards.has(card):

And a variant which removes cards as they are picked:

var picked_cards = []
while len(picked_cards) < how_many:
	var picked_index = randi() % len(cards)
	var card = cards[picked_index]

@zylann thanks it worked well, but i am unable to get list of remaing cards,
i tried:

var rameincards = list(set(cards)-set(picked_cards))

how to substract list from list for remaing cards.

praveenyadav1602 | 2020-04-08 18:53

To obtain the list of remaining card you might want to try the last snippet I proposed, which removes picked cards from the array.

Zylann | 2020-04-08 18:54