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]
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)

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.