pythonbeginner pythonbeginner - 2 months ago 8
Python Question

Error when trying to get the union, intersection and difference in a set

As the title says, I am getting an error in my code here:

#!/usr/bin/python3

import random

A = random.sample(set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 5)

B = random.sample(set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 5)


print(A | B)

print(A & B)

print(A - B)


The error I'm getting is
TypeError: unsupported operand type(s) for |: 'list' and 'list'.
I have also tried
random.sample(range(10), 5)
, which still does not work.

Is there anything I'm doing wrong?

Answer

So, as error says, function:

random.sample  

returns list object not set , try convert them like this :

A = set(random.sample(range(1,10), 5))