On Fri, 20 Nov 2015 03:05 pm, Seymore4Head wrote: > Why does a work and b doesn't? What I was trying to accomplish with b > is to get a random list (of random length) that could have digits > repeat. > > I got idea for both methods from the Internet. I do see that one uses > brackets and the other doesn't, but I don't know the difference. > > import random > for i in range (5): > a = random.sample(range(10), random.randrange(3,6)) > print a
Break it up, step by step. range(10) produces a list from 0 to 9. random.randrange(3, 6) produces a single integer from 3 to 5 (6 is excluded). Let's say by chance it produces the number 4. Then random.sample takes the list, and the integer 4, and selects 4 values at random from the list. Say, something like this: [8, 6, 7, 0] Note that random.sample does NOT repeat selections. The numbers will always be unique. > for i in range (5): > b = [random.randrange (10), random.randrange(4,8)] > print b As above, run through this step by step. random.randrange(10) produces a single number at random between 0 and 9 (10 is excluded). Let's say it picks 8. random.randrange(4,8) produces a single number at random between 4 and 7 (8 is excluded). Let's say it picks 5. Then b is set to the list [8, 5]. This list will always have two items. If you want a random number of digits that might repeat: [random.randrange(10) for i in range(random.randrange(1, 21))] will produce a random number between 1 and 20 (21 is excluded). Let's say it picks 6. then range(6) produces the list [0, 1, 2, 3, 4, 5], and "for i in range..." will iterate over those values. Although i is not used, this ends up looping 6 times. For each loop, random.randrange(10) produces a random digit between 0 and 9 (10 is excluded). So we end up with something like: [6, 4, 2, 2, 6, 9] for example. -- Steven -- https://mail.python.org/mailman/listinfo/python-list