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]
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.
0 Comments