37

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.
1
  • 5
    it is called a 'list comprehension' Commented Jul 13, 2012 at 23:00

2 Answers 2

89

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.