0

I have the following in code; which I forgot where I got it or what's it called (I'm new to Python):

deck = [Card(x, y) for x in cards for y in suits]

From the above code, I am trying to create multiple decks into a list, so that the user inputs the number of decks. I have been trying to do it like this:

decks = 2
i = 0
while i < decks:
    deck = [Card(x, y) for x in cards for y in suits]
    i += 1

But that just overwrites the current deck variable. I also tried:

decks = 2
deck = []
i = 0
while i < decks:
    deck.append(Card(x, y) for x in cards for y in suits)
    i += 1

But I only get <generator object <genexpr> at 0x04562C30> and <generator object <genexpr> at 0x04562BF0> as output when I print the contents of the deck. How exactly do I achieve what I want and how do the two for loops work in the creation of the list?

I tried the following to iterate over the members of the list; doesn't work:

for x in deck:
    for j in x:
        print(str(deck[x][j]))
2
  • That is called list comprehension. Commented Nov 20, 2018 at 12:36
  • 5
    deck.append([...])? Commented Nov 20, 2018 at 12:37

3 Answers 3

12

Try this:

deck.append([Card(x, y) for x in cards for y in suits])

This will be a list of lists. but I think all of the items will be the same in that list.

EDIT:

for x in deck:
    for j in x:
        print(j) # or do what you want, j is that inner element
Sign up to request clarification or add additional context in comments.

7 Comments

How do I iterate over the members of the inner lists? Do I need two loops for that?
Yes, you need two loop for accessing all of them but individually you can deck[i][j]. i and j will be the Integer indexes.
You can iterate over them and flat the like this: [member for l in deck for member in l]
Could you edit the answer to include how to iterate over the members please. I have edited my question what I tried and it doesn't work.
sure,just print(j) instead of str(deck[x][j])
|
2

You should change this,

deck.append(Card(x, y) for x in cards for y in suits)

into this:

deck.append([Card(x, y) for x in cards for y in suits])

Instead of appending a generator object each iteration of the list comprehension, which is what the first line does, the second line stores the data in a list and then appends it.

Comments

1

Just adding a comprehension version for the sake of completion.

decks = 2

deck = [[(x,y) for x in cards for y in suits] for i in range(decks)]

2 Comments

Would this create a single list or two lists in a list?
2 Lists in a list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.