ERJAN ERJAN - 7 months ago 8
Python Question

How do I declare list in python using for loop in one line?

d = list()

for i in range(0,10):
d.append(i)

print(d)


This does work, but is there way to write something like this:

d = list(for i in range(0,10) ) #produces a list of [0,1,2...9]
d = [ d.append(for i in range(0,10))]


Is there one liner way to declare list in python using for loop inside it?

Answer

Yes, there's a way. What you're needing is called: List Comprehensions

And you can do something like this:

d = [ i for i in range(0,10)]

which is similar to say:

d = list()
for i in range(0,10):
    d.append(i)
Comments