Here's how you can access the indices and array's elements using for-in loops.
1. Looping elements with counter and +=
operator.
items = [8, 23, 45, 12, 78]
counter = 0
for value in items:
print[counter, value]
counter += 1
Result:
# 0 8
# 1 23
# 2 45
# 3 12
# 4 78
2. Looping elements using enumerate[]
method.
items = [8, 23, 45, 12, 78]
for i in enumerate[items]:
print["index/value", i]
Result:
# index/value [0, 8]
# index/value [1, 23]
# index/value [2, 45]
# index/value [3, 12]
# index/value [4, 78]
3. Using index
and value
separately.
items = [8, 23, 45, 12, 78]
for index, value in enumerate[items]:
print["index", index, "for value", value]
Result:
# index 0 for value 8
# index 1 for value 23
# index 2 for value 45
# index 3 for value 12
# index 4 for value 78
4. You can change the index
number to any increment.
items = [8, 23, 45, 12, 78]
for i, value in enumerate[items, start=1000]:
print[i, value]
Result:
# 1000 8
# 1001 23
# 1002 45
# 1003 12
# 1004 78
5. Automatic counter incrementation with
range[len[...]]
.
items = [8, 23, 45, 12, 78]
for i in range[len[items]]:
print["Index:", i, "Value:", items[i]]
Result:
# ['Index:', 0, 'Value:', 8]
# ['Index:', 1, 'Value:', 23]
# ['Index:', 2, 'Value:', 45]
# ['Index:', 3, 'Value:', 12]
# ['Index:', 4, 'Value:', 78]
6. Using for-in loop inside function.
items = [8, 23, 45, 12, 78]
def enum[items, start=0]:
counter = start
for value in items:
print[counter, value]
counter += 1
enum[items]
Result:
# 0 8
# 1 23
# 2 45
# 3 12
# 4 78
7. Of course, we can't forget about while
loop.
items = [8, 23, 45, 12, 78]
counter = 0
while counter < len[items]:
print[counter, items[counter]]
counter += 1
Result:
# 0 8
# 1 23
# 2 45
# 3 12
# 4 78
8. yield
statement returning a generator object.
def createGenerator[]:
items = [8, 23, 45, 12, 78]
for [j, k] in enumerate[items]:
yield [j, k]
generator = createGenerator[]
for i in generator:
print[i]
Result:
# [0, 8]
# [1, 23]
# [2, 45]
# [3, 12]
# [4, 78]
9. Inline expression with for-in loop and lambda
.
items = [8, 23, 45, 12, 78]
xerox = lambda upperBound: [[i, items[i]] for i in range[0, upperBound]]
print[xerox[5]]
Result:
# [[0, 8], [1, 23], [2, 45], [3, 12], [4, 78]]
If you’re moving to Python from C or Java, you might be confused by Python’s for
loops. Python doesn’t actually have for loops… at least not the same kind of for
loop that C-based languages have. Python’s for
loops are actually foreach loops.
In this article I’ll compare Python’s for
loops to those of other languages and discuss the usual ways we solve common problems with
for
loops in Python.
For loops in other languages
Before we look at Python’s loops, let’s take a look at a for loop in JavaScript:
1 2 3 4 |
|