Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

loops

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. 
like image 957
Wang-Zhao-Liu Q Avatar asked Jul 13 '12 22:07

Wang-Zhao-Liu Q


People also ask

How FOR loop works on list in Python?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by refering to their indexes. Remember to increase the index by 1 after each iteration.

What is loop in Python in list?

A loop is a sequence of instructions that is continually repeated until a certain condition is reached. For instance, we have a collection of items and we create a loop to go through all elements of the collection. In Python, we can loop over list elements with for and while statements, and list comprehensions.

What is the purpose of for loops in Python?

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.


2 Answers

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] 
like image 115
Levon Avatar answered Sep 24 '22 14:09

Levon


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.

like image 44
Bryan Oakley Avatar answered Sep 24 '22 14:09

Bryan Oakley