What does a for loop within a list do in Python?

Question:

Can someone explain the last line of this Python code snippet to me?

Cell is just another class. I don’t understand how the for loop is being used to store Cell objects into the Column object.

class Column(object):

    def __init__(self, region, srcPos, pos):

        self.region = region
        self.cells = [Cell(self, i) for i in xrange(region.cellsPerCol)] #Please explain this line.
Asked By: Wang-Zhao-Liu Q

||

Answers:

It is the same as if you did this:

def __init__(self, region, srcPos, pos):
    self.region = region
    self.cells = []
    for i in xrange(region.cellsPerCol):
        self.cells.append(Cell(self, i))

This is called a list comprehension.

Answered By: Bryan Oakley

The line of code you are asking about is using list comprehension to create a list and assign the data collected in this list to self.cells. It is equivalent to

self.cells = []
for i in xrange(region.cellsPerCol):
    self.cells.append(Cell(self, i))

Explanation:

To best explain how this works, a few simple examples might be instructive in helping you understand the code you have. If you are going to continue working with Python code, you will come across list comprehension again, and you may want to use it yourself.

Note, in the example below, both code segments are equivalent in that they create a list of values stored in list myList.

For instance:

myList = []
for i in range(10):
    myList.append(i)

is equivalent to

myList = [i for i in range(10)]

List comprehensions can be more complex too, so for instance if you had some condition that determined if values should go into a list you could also express this with list comprehension.

This example only collects even numbered values in the list:

myList = []
for i in range(10):
    if i%2 == 0:     # could be written as "if not i%2" more tersely
       myList.append(i)

and the equivalent list comprehension:

myList = [i for i in range(10) if i%2 == 0]

Two final notes:

  • You can have “nested” list comrehensions, but they quickly become hard to comprehend 🙂
  • List comprehension will run faster than the equivalent for-loop, and therefore is often a favorite with regular Python programmers who are concerned about efficiency.

Ok, one last example showing that you can also apply functions to the items you are iterating over in the list. This uses float() to convert a list of strings to float values:

data = ['3', '7.4', '8.2']
new_data = [float(n) for n in data]

gives:

new_data
[3.0, 7.4, 8.2]
Answered By: Levon

the above-featured question is an example of using the for loop or any other condition while assigning the value in the list. although all the solutions are perfectly giving the explanation. but here is the article that will explain this concept very well.

How to use for loop inside a list.

Answered By: yash pal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.