Jason7261
Jason7261

Reputation: 145

How to reference a list within a function?

I am trying to use the for loop to do that: when the stack number = 'Stack 1', when the suit type is 'Suit A', it will run the card_red function the number of times specified in the third item in the first list (9)

game1 = \
[['Stack 1', 'Suit A', 9, 6],
['Stack 2', 'Suit B', 5, 0]]


def deal_cards():
    if     == 'Stack 1':
        if      == 'Suit A':
            for i in range(     ):
                card_red(stack1_xpos, stack1_ypos)

So what do I put after each "if" statement and in the range() brackets?

Upvotes: 0

Views: 530

Answers (4)

N Chauhan
N Chauhan

Reputation: 3515

It appears you have a list of lists. Use index notation with square brackets to access individual elements of a list.

def deal_cards():
    if game1[0][0] == 'Stack 1':
        if game1[0][1] == 'Suit A':
            for i in range(game1[0][2]):
                card_red(stack1_xpos, stack1_ypos)

Notice here that in each case, first I use index [0] to access the first sub-list, then a second index to access the individual element. Remember that the first item has an index of 0, the second is index 1, etc.

If you want to repeat this for each sub list, it is easier to pass it in as an argument to deal_cards:

def deal_cards(game):
    if game[0] == 'Stack 1':
        if game[1]== 'Suit A':
            for i in range(game[2]):
                card_red(stack1_xpos, stack1_ypos)


for game in game1:
    deal_cards(game)

And notice now that there are only single index accesses in the function whereas before there were double index accesses. This is because the game variable already will hold a sublist when called.

Upvotes: 2

Lanting
Lanting

Reputation: 3068

You can use enumerate to loop over a list of items, while also getting the position of the item:

game1 = \
[['Stack 1', 'Suit A', 9, 6],
['Stack 2', 'Suit B', 5, 0]]


def deal_cards():
  for (idx, stack) in enumerate(game1):
    if stack[0] == 'Stack 1':
        if stack[1] == 'Suit A':
            for i in range(stack(2)):
                card_red(idx, 3)

So Your loop will run twice,

  • first with idx = 0 and stack = ['Stack 1', 'Suit A', 9, 6],
  • then with idx = 1 and ['Stack 2', 'Suit B', 5, 0]

Upvotes: 1

Rarblack
Rarblack

Reputation: 4664

You can try below:

game1 = \
[['Stack 1', 'Suit A', 9, 6],
['Stack 2', 'Suit B', 5, 0]]


def deal_cards(arr):
    if arr[0] == 'Stack 1':
        if arr[1] == 'Suit A':
            for i in range(arr[2]):
                card_red(stack1_xpos, stack1_ypos)

for game in game1:
    deal_cards(game) # you can call in this way

Upvotes: 2

Harsha Biyani
Harsha Biyani

Reputation: 7268

You can try:

game1 = [['Stack 1', 'Suit A', 9, 6],['Stack 2', 'Suit B', 5, 0]]

def deal_cards():
    if game1[0][0] == "Stack1":
        if game1[0][1] == "Suit A":
            for i in range(game1[0][2]):
                card_red(stack1_xpos, stack1_ypos)

Upvotes: 2

Related Questions