test = [random.randint(1,10) for i in range(20)]

Can someone what does the random.randint(1,10) fron to for loop does, and the square brackets around it means, make it a list?

test = [random.randint(1,10) for i in range(20)]

equals

>>> import random
>>> test=[]
>>> for i in range(20):
    #test.append(random.randint(1, 10))
    random_int=random.randint(1, 10)
    test.append(random_int)

It should give you a list of 20 random numbers between 1 and 10

e.g. [3,6,7,1,9.......]

It's not really written the "python way" which encourages transparent readable code!

hth

:-D

The square brackets are part of a construction called a 'list comprehension'. The basic syntax is

[x for blah in yourlist]

The idea is to create a list quickly in one line. And as StrikerX11 noted, it's exactly the same as

tmp = []
for blah in yourlist:
    tmp.append(x)

(Usually, x and blah have some relationship to each other, but as you can see in this case, not always).

It's not really written the "python way" which encourages transparent readable code!

I wonder what the clearest way to write that would be. I found myself saying, "That's how I'd do it..."

Jeff

Once you get familiar with constructs like list comprehension, they become quite easy to read. List comprehensions also give quite an improvement in speed too.

This question has already been answered. Start a new discussion instead.