Python utilizes a for loop to iterate over a list of elements. This is different to C or Java, which use the for loop to change a value in steps and access something such as an array using that value.
For loops iterate over collection based data structures like [lists](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/guide/english/python/lists), tuples, and dictionaries.
In general, you can use anything as the iterator value, where entries of the iterable can be assigned to. E.g. you can unpack tuples from a list of tuples:
Rather than being a function, range is actually an immutable sequence type. The output will contain results from lower bound i.e 0 to the upper bound i.e 10 but excluding 10. By default, the lower bound or the starting index is set to zero.
for i in range(4,10,2): #From 4 to 9 using a step of two
print(i)
```
Output:
```
>
4
6
8
>
```
**xrange() function**
For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and xrange returns an xrange object. It means that xrange doesn't actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators.
One more thing to add. In Python 3.x, the xrange function does not exist anymore. The range function now does what xrange does in Python 2.x
**Iterate over a list and get the corresponding index with the enumerate() function**
```python
A = ["this", "is", "something", "fun"]
for index,word in enumerate(A):
print(index, word)
```
Output:
```
>
0 this
1 is
2 something
3 fun
>
```
A common use case is iterating over a dictionary:
```python
for name, phonenumber in contacts.items():
print(name, "is reachable under", phonenumber)
```
If you absolutely need to access the current index of your iteration, do **NOT** use `range(len(iterable))`! This is an extremely bad practice and will get you plenty of chuckles from senior Python developers. Use the built in function `enumerate()` instead:
Python permits you to use else with for loops. The else case is executed when none of the conditions within the loop were satisfied. To use the else we have to make use of `break` statement so that we can break out of the loop on a satisfied condition. If we do not break out then the else part will be executed.
A interesting fact is that for loop is a bit faster compared to while loop in python. Because in for loop range/xrange is used which is implemented in C(in python's library) whereas in while loop we make use of some incremental statement specifically at the end of sentence like (i+=1) which is interpreted. Thus for loop is faster than while loop. Reference: