1

What is the shortest way to get to two distinct lists, a, and b, which contain random integers.

I currently have:

(a,b)=([randint(0,30)for x in range(10)][randint(0,30)for x in range(10)])

or

a=[randint(0,30)for x in range(10)]
b=[randint(0,30)for x in range(10)]

Using

a=b=[randint(0,30)for x in range(10)]

produces two identical lists.

Is there a shorter way to do this?

2
  • 4
    Are you charged by the character? I'd maybe extract the list generation to a function and call it twice, but there's nothing terrible about your second version.
    – jonrsharpe
    Commented Nov 12, 2016 at 14:02
  • Where you say "produces two identical lists", you're misunderstanding what's going on. The code produces ONE list, you just have two names referring to that one list. Commented Nov 12, 2016 at 14:13

1 Answer 1

2

You can use random.sample:

from random import sample

r = range(0,30)
a, b = sample(r, 10), sample(r, 10)
3
  • 1
    This isn't quite the same, as it samples without replacement.
    – jonrsharpe
    Commented Nov 12, 2016 at 14:41
  • @jonrsharpe Yes the assignment is the same, but the way those two lists are gotten is different (shorter).
    – Kenly
    Commented Nov 15, 2016 at 7:35
  • I'm not sure you understood my point: the original version could create a list like [29, 5, 29, ...], repeating a number within the ten, which this version cannot. It's not just a different way, but leads to a different set of outputs. The acceptance suggests that this isn't a deal breaker for the OP (or they haven't thought of it) but I thought it should be noted for other users with similar problems.
    – jonrsharpe
    Commented Nov 15, 2016 at 7:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.