1

I have been trying to shuffle a list in specific manner:

def shuffle(card_deck):
shuffled = list()
deck_size = len(card_deck) // 2

lhand_deck = card_deck[0: deck_size]
rhand_deck = card_deck[deck_size: deck_size*2]

for i, j in zip(lhand_deck, rhand_deck):
    shuffled.append(i); shuffled.append(j)

return shuffled

To improve the perform for a larger deck, I decided to use list comprehension:

shuffled = [
    i
    for i in zip(lhand_deck, rhand_deck)
]

Now the the list contains tuple however I want it contain it single element:

shuffled = [0, 2, 1, 3]

instead of

shuffled = [(0,2), (1, 3)]

The * doesn't work it this case since it throws error. Is there any method to it or a loop can only be used? Thanks for help

UbadahJ
  • 46
  • 6
  • You can use as mentioned in the duplicate `list(sum(shuffled, ()))`. This is of course just one of the several other ways in the duplicate – Sheldore Jan 09 '19 at 19:16
  • List comprehension will only marginally improve performance, and this improvement disappears if you cache the append methods manually – juanpa.arrivillaga Jan 09 '19 at 19:35

2 Answers2

2

You can use a nested list comprehension to flatten the output instead:

shuffled = [
    i
    for t in zip(lhand_deck, rhand_deck)
    for i in t
]
blhsing
  • 91,368
  • 6
  • 71
  • 106
1

You could use itertools.chain to flatten the list of tuples:

shuffled = list(chain.from_iterable(zip(lhand_deck, rhand_deck)))

Which would give for this example list:

shuffle([1,3,5,2,1])
[1, 5, 3, 2]
yatu
  • 86,083
  • 12
  • 84
  • 139