0

hello,

I think it is just a silly thing but i can't work out why im only getting one number back from this..?

def MakeList(n): # Returns a list of n random numbers
    List = []
    for i in range(0, n):
        List.append(random.randint(0,1000))
        return (List)
MakeList(10)

I get:

[546]

But if I say,

def MakeList(n): # Returns a list of n random numbers
    List = []
    for i in range(0, n):
        List.append(random.randint(0,1000))
        print (List)
MakeList(10)

I get:

[935]
[935, 64]
[935, 64, 323]
[935, 64, 323, 584]
[935, 64, 323, 584, 806]
[935, 64, 323, 584, 806, 833]
[935, 64, 323, 584, 806, 833, 144]
[935, 64, 323, 584, 806, 833, 144, 347]
[935, 64, 323, 584, 806, 833, 144, 347, 526]
[935, 64, 323, 584, 806, 833, 144, 347, 526, 615]
3
Contributors
2
Replies
21
Views
4 Years
Discussion Span
Last Post by vegaseat
1
for i in range(0, n):
    List.append(random.randint(0,1000))
    return (List)

This generates one number, appends that one number, and returns immediately on the first iteration of the loop. You need to move the return statement outside of the loop:

for i in range(0, n):
    List.append(random.randint(0,1000))

return (List)
0

Might as well take advantage of module random ...

def make_list2(n):
    return random.sample(range(1000), n)

print(make_list2(10))

In Python2 use xrange() for large numbers. In Python3 range() is a generator.

Edited by vegaseat

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.