3

Hi I am trying to define a function that returns a shuffled list l1 without changing the original list l using the method random.shuffle but I got this error message:

builtin_function_or_method object has no attribute shuffle

import random
def shuffle_list(l):
  l1=random.shuffle(l)
  return(l1)
martineau
  • 119,623
  • 25
  • 170
  • 301
Axel
  • 31
  • 1
  • 1
  • 2

4 Answers4

3
from random import shuffle
def shuffle_list(l):
  def shuffle_list(l):
    shuffle(l)
    return l

Import shuffle directly and return l and don't save it into any variable because l1 = shuffle(l) will return None

I know this is coming late.

Rexben
  • 339
  • 4
  • 13
1

Replace all instances of random.shuffle() with shuffle() after changing the import random with from random import shuffle.

PinkBanter
  • 1,686
  • 5
  • 17
  • 38
0

random.shuffle changes the order of the list in place and returns None.

>>> lst = [1,2,3]
>>> shuffle_list(lst)
>>> print lst
[3, 1, 2]
>>> shuffle_list(lst)
>>> print lst
[1, 3, 2]

So if you don't care about the order of the original list, your code could simply be:

import random
random.shuffle(l)
Marissa Novak
  • 544
  • 3
  • 6
  • but the original list changes when I use the simple method, i wanna a shuffled copy, without modifying the original list – Axel Jun 01 '17 at 01:46
  • 1
    In that case, someone answered that here: https://stackoverflow.com/a/12978830/6616057 – Marissa Novak Jun 01 '17 at 01:48
0

random.shuffle() modifies the list in-place and doesn't return anything, so you need to first make a copy of the list argument, shuffle, and then return it, in order to preserve the original:

import random

def shuffle_list(lst):
    lst2 = lst.copy()
    random.shuffle(lst2)
    return lst2

items = list(range(10))
shuffled = shuffle_list(items)

print(items)    # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(shuffled) # => [6, 2, 1, 9, 3, 0, 8, 4, 5, 7] (or some other rearrangement)
martineau
  • 119,623
  • 25
  • 170
  • 301
  • Can anyone please explain the error message, even if i apply the method on a copy nothing changes – Axel Jun 01 '17 at 22:46