-1

Purely as a learning experience I've started a basic Python script. At the moment, it's supposed to simulate a shuffled deck of standard playing cards. My script works as expected, except for the shuffling part.

import random

deck = list()
# play_deck = list()
suits = ['hearts', 'clubs', 'diamonds', 'spades']
card = {'suit':'', 'faceval': ''}

i = 0
for suit in suits:
    j = 1
    while j < 14:
        card = {'suit': suit, 'faceval': str(j)}
        deck.append(card)
        j+=1
i+=1


deck = random.shuffle(deck)

for card in deck:
    print(card['suit'])
    print(card['faceval'])

I create the deck using a list of suits and a for loop to get four suits of 13 cards each, and then print each deck list memberm (card) to the console to see that it's working as expectecd.

But when I add random.shuffle() into the code, I get this error:

TypeError: 'NoneType' object is not iterable

I've tried these techniques:

deck = random.shuffle(deck)

play_deck = random.shuffle(deck)

Why I can't iterate over the deck after running it through random.shuffle() function? Am I missing something?

2 Answers2

0

random.shuffle(lst) modifies lst in-place, and returns None (like lst.sort()).

Instead of

deck = random.shuffle(deck)

do

random.shuffle(deck)
AKX
  • 152,115
  • 15
  • 115
  • 172
-1

https://docs.python.org/3/library/random.html#random.shuffle

random.shuffle(x) Shuffle the sequence x in place.

To shuffle an immutable sequence and return a new shuffled list, use sample(x, k=len(x)) instead.