using for loop to create list | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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']

16th Jul 2017, 10:42 PM
Avnish Vishwakarma
Avnish Vishwakarma - avatar
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.
17th Jul 2017, 1:14 AM
Venkatesh Pitta
Venkatesh Pitta - avatar
0
does that 'i' before 'for' corresponds to the element which will be created by the values given by for loop
17th Jul 2017, 11:40 AM
Avnish Vishwakarma
Avnish Vishwakarma - avatar