Skip to content
  • Home
  • Contact Us
  • About Us
  • Privacy Policy
  • DMCA
  • Linkedin
  • Pinterest
  • Facebook
thecscience

TheCScience

TheCScience is a blog that publishes daily tutorials and guides on engineering subjects and everything that related to computer science and technology

  • Home
  • Human values
  • Microprocessor
  • Digital communication
  • Networking
  • Toggle search form

How to use for loop inside a list in python

Posted on October 9, 2022 By YASH PAL No Comments on How to use for loop inside a list in python

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

Post navigation

Previous Post: HackerEarth K-th mean path problem solution
Next Post: How to Delete a git branch remote/local branch

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Pick Your Subject
Human Values

Copyright © 2023 TheCScience.

Powered by PressBook Grid Blogs theme