Python for loop generates list? [closed]

First the expression is called list comprehension. Its used to create a new list as you iterate another list/iterable. A good scenario is

[value for item in range(integer)]

New array is generated [], the values of that array will depend on the value from the expression above on each iteration . Meaning if you do something line

[x for x in range(3)] # returns [0,1,2]
[x*4 for x in range(2)] # returns [0,4,8]

In such cases value can be an expression or a constant
In your case [2 for x in range(3)] # returns [2,2,2] because of each iteration the the value remains 2

I almost forget [a,b] + [c,d,e] = [a,b,c,d,e]

So to make it simple [0,1] + [2 for x in range(3)] # returns [0,1,2,2,2]

Lastly your range is too big that’s why its taking too long as mentioned in the comments!

Leave a Comment