Phil Dawson
Phil Dawson

Reputation: 9

Using append in a for loop to fill a list

Im trying to write a basic deck shuffling program, but repeatedly get an out of bounds error when i try to call any specific index in my deck list.

suits = ["spades", "diamonds", "hearts", "clubs"] 

deck = []
def createDeck(deck):
    for i in range(0,4):
        for j in range(0,13):
            c = str(j+1) + " of " + suits[i]
            return deck.append(c)

Upvotes: 0

Views: 395

Answers (3)

Aaditya Ura
Aaditya Ura

Reputation: 12669

If you want deck list without previous suits elements then define deck in the function otherwise when you will pass suits as an argument then deck will become suits list.

   suits = ["spades", "diamonds", "hearts", "clubs"]


    def createDeck(deck):
        deck=[]

        for i in range(0,4):
            for j in range(0,13):
                c = str(j+1) + " of " + suits[i]

                deck.append(c)
        return deck

    print(createDeck(suits))

Output:

['1 of spades', '2 of spades', '3 of spades', '4 of spades', '5 of spades', '6 of spades', '7 of spades', '8 of spades', '9 of spades', '10 of spades', '11 of spades', '12 of spades', '13 of spades', '1 of diamonds', '2 of diamonds', '3 of diamonds', '4 of diamonds', '5 of diamonds', '6 of diamonds', '7 of diamonds', '8 of diamonds', '9 of diamonds', '10 of diamonds', '11 of diamonds', '12 of diamonds', '13 of diamonds', '1 of hearts', '2 of hearts', '3 of hearts', '4 of hearts', '5 of hearts', '6 of hearts', '7 of hearts', '8 of hearts', '9 of hearts', '10 of hearts', '11 of hearts', '12 of hearts', '13 of hearts', '1 of clubs', '2 of clubs', '3 of clubs', '4 of clubs', '5 of clubs', '6 of clubs', '7 of clubs', '8 of clubs', '9 of clubs', '10 of clubs', '11 of clubs', '12 of clubs', '13 of clubs']

Upvotes: 0

Sadia Arif
Sadia Arif

Reputation: 231

You should return the list named as "deck" after all loops.

suits = ["spades", "diamonds", "hearts", "clubs"] 
deck = []
def createDeck(deck): 
    for i in range(0,4): 
        for j in range(0,13): 
            c = str(j+1) + " of " + suits[i] 
            deck.append(c)
    return deck

Upvotes: 1

metl wolf
metl wolf

Reputation: 91

suits = ["spades", "diamonds", "hearts", "clubs"]
deck = [] 
def createDeck(deck):
    for i in range(0,4):
        for j in range(0,13):
            c = str(j+1) + " of " + suits[i]
            return deck.append(c)

Assuming this is what you had, your deck[] will only contain one item because you returned from the function on the first step of your for loop. Lose the return and your good to go.

Upvotes: 0

Related Questions