+ 1
using for loop to create list
Why this statement does not execute? >>>y=[for i in range(5)] SyntaxError: invalid syntax Why below statement executes without an error? >>> y=[str(i)for i in range(5)] >>> print(y) ['0', '1', '2', '3', '4']
2 Answers
+ 5
y = [i for i in range(5)] is how the first statement should be.
it can also be written as y = list(range(5)) since range returns a generator.
0
does that 'i' before 'for' corresponds to the element which will be created by the values given by for loop