Skip to content Skip to sidebar Skip to footer

Shuffle List With Empty (or None) Elements

I've got some list of lists and it values can be empty [] or NoneType lst = [[[]], [1, None], 2, [[], 3], 4] And I need to randomise them. To get [[1, None], 4, 2, [[], 3], [[]]],

Solution 1:

You want to make sure you shuffle in place before print or assignment.

>>>from random import shuffle>>>lst = [[[]], [1, None], 2, [[], 3], 4]>>>shuffle(lst)>>>print(lst)
[2, 4, [[], 3], [1, None], [[]]]

Solution 2:

From the comments:

The problem is in misunderstanding of how random.shuffle works. You've tried to iterate through the returned value which is None, because shuffle returns nothing and changes its argument in-place.

Here's how you can solve this problem:

lst = [[[]], [1, None], 2, [[], 3], 4]
shuffle(lst) # Don't capture the return value# lst is now shuffled and you can put it into `for` loop:
for x in lst:
    # something

Solution 3:

Glad you found the answer (that random.shuffle modifies the list in-place and returns None) - however, if you wanted to leave the list unmodified and get a "shuffled" result, then:

import random
shuffled = sorted(lst, key=lambda L: random.random())

Will do that for you.

Post a Comment for "Shuffle List With Empty (or None) Elements"