How do I put this code into one print function (or line)?

Viewed 115

So I want to make this code into a single line. I have no idea how to create two random lists and then print out the common numbers that are in the two lists all within one line. I am new to putting code into one line and I have no idea if this is possible.

Here is the code that I have:

import random
a, b = random.sample(range(1, 50), 30), random.sample(range(1, 50), 30)

print([x for x in a for y in b if x == y])

And here is my try at this:

import random
print([[a = random.sample(range(1, 50), 30)], [b = random.sample(range(1, 50), 30)], x for x in a for y in b if x == y])
2 Answers

Just embed the definitions since there's no need for a variable:

import random
print([x for x in random.sample(range(1, 50), 30) for y in random.sample(range(1, 50), 30) if x == y])

You can also replace random with __import__("random") then get rid of the import random on the first line if you want a true one-liner.

With sets:

>>> import random
>>> {*random.sample(range(1, 50), 30)}.intersection({*random.sample(range(1, 50), 30)})
Related