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?

Recommended Answers

All 4 Replies

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.

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.