In Python you can iterate over the list itself:
for item in my_list:
#do something with item
or to use indices you can use xrange():
for i in xrange(1,len(my_list)): #as indexes start at zero so you
#may have to use xrange(len(my_list))
#do something here my_list[i]
There's another built-in function called enumerate(), which returns both item and index:
for index,item in enumerate(my_list):
# do something here
examples:
In [117]: my_lis=list('foobar')
In [118]: my_lis
Out[118]: ['f', 'o', 'o', 'b', 'a', 'r']
In [119]: for item in my_lis:
print item
.....:
f
o
o
b
a
r
In [120]: for i in xrange(len(my_lis)):
print my_lis[i]
.....:
f
o
o
b
a
r
In [122]: for index,item in enumerate(my_lis):
print index,'-->',item
.....:
0 --> f
1 --> o
2 --> o
3 --> b
4 --> a
5 --> r
Answer from Ashwini Chaudhary on Stack OverflowFor loop with list
What does a for loop within a list do in Python? - Stack Overflow
Iterate through a list and perform an action for each item in the list
Iterating over a list in python using for-loop - Stack Overflow
Videos
In Python you can iterate over the list itself:
for item in my_list:
#do something with item
or to use indices you can use xrange():
for i in xrange(1,len(my_list)): #as indexes start at zero so you
#may have to use xrange(len(my_list))
#do something here my_list[i]
There's another built-in function called enumerate(), which returns both item and index:
for index,item in enumerate(my_list):
# do something here
examples:
In [117]: my_lis=list('foobar')
In [118]: my_lis
Out[118]: ['f', 'o', 'o', 'b', 'a', 'r']
In [119]: for item in my_lis:
print item
.....:
f
o
o
b
a
r
In [120]: for i in xrange(len(my_lis)):
print my_lis[i]
.....:
f
o
o
b
a
r
In [122]: for index,item in enumerate(my_lis):
print index,'-->',item
.....:
0 --> f
1 --> o
2 --> o
3 --> b
4 --> a
5 --> r
Yes you can, with range [docs]:
for i in range(1, len(l)):
# i is an integer, you can access the list element with l[i]
but if you are accessing the list elements anyway, it's more natural to iterate over them directly:
for element in l:
# element refers to the element in the list, i.e. it is the same as l[i]
If you want to skip the the first element, you can slice the list [tutorial]:
for element in l[1:]:
# ...
can you do another for loop inside this for loop
Sure you can.
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]
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.
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 + 1print(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?
When you do for i in row, i takes the values in row, i.e. '1', then '2', then '3'.
Those are strings, which are not valid as a list index. A list index should be an integer. When doing range(len(row)) you loop on integers up to the size of the list.
By the way, a better approach is:
for elt_id, elt in enumerate(list):
# do stuff
Given row = ['1', '2', '3'], each item inside row is a string, thus it can be easily printed:
for i in row:
print(i)
However, in your second example you are trying to access row using a string. You need an integer to access values inside a list, and row is a list! (of strings, but a list still).
for i in row:
# row[i] = int(row[i]) -> this will throw an error
row[int(i)] = int(row[int(i)]) # this will throw an error