Par Kho
Par Kho

Reputation: 1

how to make a list with functions

i have a function that makes random values in a list. now i want to make a list that indexes are these random lists. the random maker function :

def ran():
     h1=random.randint(40,240)
     h2=random.randint(40,240)
     h3=random.randint(80,240)
     t1=random.randint(5,20)
     t2=random.randint(5,20)
     t3=random.randint(4,12)
     xx=[h1,t1,h2,t2,h3,t3]
     return xx

next function :

def particle(xj):
    for j in range(20):
        xj[j]=ran()
        return xj

this function only gave me the first index, i want 20. how can i fix it? this is what i get for example :

[[176, 8, 83, 5, 110, 12]]

(first function works perfectly)

Upvotes: 0

Views: 71

Answers (2)

youkaichao
youkaichao

Reputation: 2364

the position of return is wrong.

you should put it like:

def particle():
    xj = [0 for x in range(20)]
    for j in range(20):
        xj[j]=ran()
    return xj

Upvotes: 3

Attersson
Attersson

Reputation: 4866

Easy, quicker and more performant, using list comprehension:

def particle():
    return [ran() for _ in range(20)]

Usage:

xj = particle()

Upvotes: 1

Related Questions