Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (47.6k points)

I have a list of objects in Python and I want to shuffle them. I thought I could use the random.shuffle method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?

import random 

class a: 

  foo = "bar" 

a1= a() 

a2= a() 

b = [a1,a2] 

print random.shuffle(b)

This will fail.

1 Answer

0 votes
by (106k points)
  • In My code random.shuffle works, here's an example regarding that:

from random import shuffle 

x = [[i] for i in range(10)] 

shuffle(x)

print x 

  • You should also keep this thing in mind that shuffle does not return any value

  • For your code, you just need to replace some line of code which I am doing down here:-

import random

class a:

    foo = "bar"

a1= a()

a2= a()

b = [a1,a2]

random.shuffle(b)

print(b)

image

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 22, 2019 in Python by Sammy (47.6k points)
+2 votes
3 answers
asked May 21, 2019 in Python by Aditya98 (1.3k points)
0 votes
1 answer
asked Jul 2, 2019 in Python by Anurag (33.1k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...