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]
Answer from Levon on Stack Overflow
🌐
W3Schools
w3schools.com › python › python_lists_loop.asp
Python - Loop Lists
List Comprehension offers the shortest syntax for looping through lists: A short hand for loop that will print all items in a list: thislist = ["apple", "banana", "cherry"] [print(x) for x in thislist] Try it Yourself » · Learn more about ...
Top answer
1 of 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]
2 of 2
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.

Discussions

For loop with list
First I need to make a list of names: sailors = [“Jan”, “Piet”, “Joris”, “Korneel”] Then I need to ask the user to input his/her name: name = input (“Type your name please”.) Then, and HERE is my problem, I need to use a for loop to check if the name is in the list. More on discuss.python.org
🌐 discuss.python.org
0
0
February 28, 2023
Iterate through a list and perform an action for each item in the list
There will probably be a more elegent way to do this (and I hope someone can point this out to me) but this should work: for i, item1 in enumerate(desciption_list): for j, item2 in enumerate(desciption_list): if j <= i: continue else: print(jaro_distance(str(item1), str(item2)) Just found this on StackOverflow : import itertools for a, b in itertools.combinations(mylist, 2): print(jaro_distance(a, b)) More on reddit.com
🌐 r/learnpython
7
29
November 12, 2021
Creating lists using for loops
You wouldn't create new variables for each list. You'd add those lists into another list, then you'd just index into the outer list to get the inner lists. But yes, this is very possible. Trivial even with something like a list comprehension. More on reddit.com
🌐 r/learnpython
2
2
November 14, 2021
how to best compare two lists using a for loop?
You're comparing the entry in a (call it x) with the entry at the xth position in b. If you want to go through things stepwise like this, consider using the enumerate function to keep indices consistent. newlist = [] for i, value in enumerate(a): if a[i] == b[i]: newlist.append(i) print(newlist) Here's how that looks as a list comprehension: print([i for i, val in enumerate(a) if a[i] == b[i]]) More on reddit.com
🌐 r/learnpython
23
9
August 17, 2022
🌐
Python.org
discuss.python.org › python help
For loop with list - Python Help - Discussions on Python.org
February 28, 2023 - First I need to make a list of names: sailors = [“Jan”, “Piet”, “Joris”, “Korneel”] Then I need to ask the user to input his/her name: name = input (“Type your name please”.) Then, and HERE is my problem, I need to use a for loop to check if the name is in the list.
🌐
GeeksforGeeks
geeksforgeeks.org › python › iterate-over-a-list-in-python
Iterate over a list in Python - GeeksforGeeks
We can also use the enumerate() function to iterate through the list. This method provides both the index (i) and the value (val) of each element during the loop. ... a = [1, 3, 5, 7, 9] # Here, i and val reprsents index and value respectively ...
Published   December 27, 2025
🌐
LearnPython.com
learnpython.com › blog › python-list-loop
7 Ways to Loop Through a List in Python | LearnPython.com
However, this time we used list comprehension to do two things: add the word ‘juice’ to the end of the list item and print it. Another method for looping through a Python list is the range() function along with a for loop.
🌐
Codecademy
codecademy.com › learn › dspath-python-lists-and-loops › modules › dspath-loops › cheatsheet
Python Lists and Loops: Python Loops Cheatsheet | Codecademy
The syntax of a for loop consists of assigning a temporary value to a variable on each successive iteration. When writing a for loop, remember to properly indent each action, otherwise an IndentationError will result.
Find elsewhere
🌐
StrataScratch
stratascratch.com › blog › looping-through-lists-in-python
Looping Through Lists in Python: A Comprehensive Tutorial - StrataScratch
April 9, 2025 - Learn how to loop through a list in Python using real Uber data, practical techniques, and performance-friendly tips.
🌐
Python
wiki.python.org › moin › ForLoop
ForLoop - Python Wiki
In Python, these are heavily used whenever someone has a list of lists - an iterable object within an iterable object. for x in range(1, 11): for y in range(1, 11): print('%d * %d = %d' % (x, y, x*y)) ... Like the while loop, the for loop can be made to exit before the given object is finished.
🌐
Reddit
reddit.com › r/learnpython › iterate through a list and perform an action for each item in the list
r/learnpython on Reddit: Iterate through a list and perform an action for each item in the list
November 12, 2021 -

Hi, so I am quite new to python however have an issue I am struggling to come up with convincing solution to.

I have a list of strings - around 27 items - and have also created a function that calculates the Jaro distance between the two String variables, this works as far as I can tell however I now need to form a loop that will allow me to apply this function for each item in the list against each other item in the list.

So far I have been using the following for loop:

for i in description_list:
    print(jaro_distance(str(description_list[1]),str(description_list[count+1])))     
    count = count + 1

print(jaro_distance(str(description_list[1]), str(description_list[count+1]))) count = count + 1

but this only works for comparing the fist item in the list vs the following items. So my question is this, how can I create a loop that iterates each item against every other item in the list?

🌐
Python Tutorial
pythontutorial.net › home › python basics › how to use a for loop to iterate over a list
How to Use a For Loop to Iterate over a List - Python Tutorial
March 26, 2025 - For example, the following defines a list of cities and uses a for loop to iterate over the list: cities = ['New York', 'Beijing', 'Cairo', 'Mumbai', 'Mexico'] for city in cities: print(city)Code language: Python (python)
🌐
Tutorialspoint
tutorialspoint.com › python › python_loop_lists.htm
Python - Loop Lists
A for loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, string, or range) or any other iterable object. It allows you to execute a block of code repeatedly for each item in the sequence.
🌐
Runestone Academy
runestone.academy › ns › books › published › fopp › Iteration › Listsandforloops.html
7.5. Lists and for loops — Foundations of Python Programming
Yes, there are nine elements in the list so the for loop will iterate nine times. ... Iteration by item will process once for each item in the sequence. Each string is viewed as a single item, even if you are able to iterate over a string itself. Error, the for statement needs to use the range ...
🌐
Lawrence
www2.lawrence.edu › fast › GREGGJ › CMSC210 › loops › for.html
Lists and for
A for loop is an iteration structure that is designed to iterate over each member of some list of data values. For each member of the list the for loop temporarily assigns the member to the variable x. In the body of the loop (the line of code following the colon) we specify what we want to ...
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python iterate over list
Python Iterate Over List - Spark By {Examples}
May 31, 2024 - You can use the enumerate function in Python to iterate over a list with both index and value. For example, the enumerate function returns pairs of index and corresponding values from the list during each iteration of the for loop.
🌐
Projectpython
projectpython.net › chapter07
Lists and for-loops - Project Python
Because for-loops are simpler and easier to read, you should use a for-loop in your code wherever the goal is to refer to the items of a list, but without changing the list. If you want to change which items the list contains, you should use a while-loop. Some functions return lists.
🌐
Programiz
programiz.com › python-programming › for-loop
Python for Loop (With Examples)
... Swift in the first iteration. Python in the second iteration. Go in the third iteration. ... The for loop iterates over the elements of sequence in order, and in each iteration, the body of the loop is executed. The loop ends after the body of the loop is executed for the last item.
🌐
GitHub
hplgit.github.io › primer.html › doc › pub › looplist › ._looplist-bootstrap002.html
Loops and lists
When data are collected in a list, we often want to perform the same operations on each element in the list. We then need to walk through all list elements. Computer languages have a special construct for doing this conveniently, and this construct is in Python and many other languages called a for loop. Let us use a for loop to print out all list elements:
🌐
Kansas State University
textbooks.cs.ksu.edu › intro-python › 07-lists › 03-loops-lists
Loops with Lists :: Introduction to Python
June 27, 2024 - So, as a general rule, we should use a for loop when we just want to iterate through the list and not make any changes to the list while inside of the loop. If we do need to make changes, it is better to use a while loop and an iterator variable to access the list elements directly.
🌐
Quora
quora.com › How-do-you-populate-a-list-using-a-loop-Python-list-loops-development
How to populate a list using a loop (Python, list, loops, development) - Quora
Good when applying a single function; yields an iterator in Python 3 (convert to list). ... Use when loop termination depends on a condition not easily expressed with for/range. ... Appending inside a loop is O(1) amortized, but large repeated growth can cost cache/GC overhead; preallocate if performance-critical. Prefer list comprehensions for readability and often better speed.