How to use for loop inside a list in python YASH PAL, October 9, 2022 In this article, we will understand using the for loop inside the list in python programming. Let’s understand this concept step by step. Let’s say we have a list “squares_values = []” and we want to append some data. let’s say wish to add 10 square values to it. so using the code we can write like this. squares_values = []for i in range(10): squares_values.append(i*i) Output - [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] The above code simply first declares the list and then using the for loop it is appending the square values of 1 to 10 in the list. so python is all about writing shortcodes. so the above code will be written in one line as shown below. squares_values = [i*i for i in range(10)] Output - [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] so here we are writing the same above three lines in one line and the output is the same. so how to use for loop inside a list. so the syntax goes like this List_Name = [value [for loop condition]] Even if I can say there is not any syntax over there because we can apply as much as conditions as we want or based on the condition. let’s say we want the use if condition inside a for loop and that for loop is used for appending the data in the list. so instead of writing the code like this. squares_values = []for i in range(10): if i%2 == 0: squares_values.append(i*i) we can simply write the code like this. squares_values = [i*i for i in range(10) if i%2 == 0] so there is nothing different between both codes. this feature is similar to like list comprehension. coding problems python