In Python 3.6.3 Is there a way to loop though one list after another?
For example:
deck = [(value, suit) for value in range(2, 11) +
["J", "Q", "K", "A"] for suit in ["H", "C", "D", "S"]]
(In this case, I want to loop through the face cards right after the non-face cards.)
For clarification: The above line throws a:
TypeError: unsupported operand type(s) for +: 'range' and 'list'
This is my problem.
range
doesn't return alist
in Python3, sorange(2, 10) + ["J", "Q", "K", "A"]
doesn't work, butlist(range(2, 10)) + ["J", "Q", "K", "A"]
does. You can also useitertools.chain
to concatenate iterables:The nested comprehension does, of course, constitute a cartesian product which you can also use a util for:
In Python3, you can use unpacking:
See @schwobaseggl's solution for what you want, but I usually prefer to represent cards as a 2 character string, however:
This is more readable in my opinion, and will still behave a lot like a tuple of rank, suit.
Focusing only in the error you do get:
I will give you an explanation.
Your current code does work in Python 2:
will print:
In Python 3 you have to use
list(range(2, 11))
:will print:
You have to use
list()
becauserange()
in Python 3 does create an immutable sequence type, not a list.The problem with your current code is here:
First off, it should be
range(2, 11)
, otherwise, cards with the number 10 are omitted. Second, in order to join the range and the list, you'll have to do like so:So the final result will be:
I think this will give you the desired output (first all non-face cards, then all face cards).