Python Functional Python Functional Rules Things Not To Do

Jason Brown
Jason Brown
6,878 Points

random.shuffle crashes when passed a range?!?! >>> some_nums = random.shuffle(range(5,250))

import random some_nums = random.shuffle(range(5,250)) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/", line 272, in shuffle x[i], x[j] = x[j], x[i] TypeError: 'range' object does not support item assignment random <module 'random' from '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/'> dir(random) ['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'BuiltinMethodType', '_MethodType', '_Sequence', '_Set', 'all', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'spec_', '_acos', '_ceil', '_cos', '_e', '_exp', '_inst', '_log', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']

2 Answers

It's also because random.shuffle returns None, since it actually shuffles a list in place.

So you'd need to use the following:

some_nums = list(range(5,250))  # make sure some_nums is a list/mutable sequence

You could also use the list comprehension that Alvin McNair suggested, but only to assign to the variable, not as an argument to the random.shuffle function.

Kenneth Love, perhaps you need another example in your video... even though it was meant to be a group of bad examples!

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Maybe so! Lists are just a source of headaches when it comes to functional programming...and yet they're your primary data type.

range(start, stop[, step]) Rather than being a function, range is actually an immutable sequence type, as documented in Ranges and Sequence Types — list, tuple, range.

Since its immutable you need to make it a list.

nums=random.shuffle([x for x in range(5,250)])