Here is an example
for i in [1, 2, 3]:
print i
Each time the loop executes, the variable "i" takes on the value of the next item in the list.
You might be used to writing code like this
x = [1, 2, 3]
for i in range(len(x)):
print x[i]
Although this works, it introduces a needless counting variable and two unnecessary function calls (range and len). The first form shown above is easier to write and more efficient.
Iterating over a part of a list
What if you just want to iterate over a part of a list? You should take a slice and iterate over the slice.
x = [1, 2, 3, 4, 5]
# iterate over the first 3 values
for i in x[:3]:
print i
Again, this is simpler than using the range function to generate a series of index values
x = [1, 2, 3, 4, 5]
# iterate over indexes 0..2
for i in range(0,3):
print x[i]
No comments:
Post a Comment