Python: For loop



Python For loop works like looping statement in other languages and iterates over array of objects. The syntax is quite similar to Java as you would see below:

Python For Loop Example

 
#!/usr/bin/python
 
for i in range(1, 5):
	print i
else:
	print 'End of python for loop'

Python For Loop similarity with Java Foreach

In Java, the syntax for foreach loop is:

for (type var : arr) {
    body-of-loop
}

Example of Java foreach loop is:

int[] ar = {1, 2, 3};
int sum = 0;
for (int d : ar) {  // d gets successively each value in ar.
    sum += d;
}

Python For Loop Using Enumerate

Here we use Python enumerate to run with Python for loop.

for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']):
    print i, season

Output of the code above is:

0 Spring
1 Summer
2 Fall
3 Winter