Iterating Through List in Python

Iterating Through List in Python

Well, at times, we need to iterate through our list, going through the different list elements for some or other reason. Let’s now explore some different things, related to iterating through the list. We can simply make use of loops, when we need to iterate through the list. Let’s see a very basic, and simple example to understand the looping in list. Basically, we are going to be using for loop more often.

As you can see in the above program, we have a simple list, and then we are iterating through the list, using the for loop. The number is a variable, and we can simply say that the number variable has one item per iteration from the list in the above example. So, in every iteration, we get a different number printed from the list.

Iterating Through List in Python

The thing is that the number is just a variable, which contains one element per iteration. So, this is not like if we are changing the value of the number variable, we are also making changes to the list. It is not going to happen. You can refer the below program, to understand the same.

As you can see in the above program, we have a simple list, and then we are iterating through the list. In the loop, we have assigned another value to the number, but this won’t reflect to the list. After the loop ends, we are printing the list as well, and we can find that the list is absolutely fine, since here, we are not accessing the element through the index. When we are accessing some element with it’s index, then the things are quite different. You can try executing the above program and observe the output.

Let’s try to access the list with the help of the index. For this, we would also require the length of the list, so we would be making use of the len function as well. Let’s have a look at the program.

As you can see in the above program, we are accessing the elements with their indexes in the list. In the range function, we are not providing the start, so it simply defaults to zero. We can loop through the list, as and when required in our python programs. You can also try printing the index variable, and you can find that we get the indexes for the list in each iteration.

You can also try using the while loop, to iterate through the list. It is very simple, where you just have to go through the indexes of the list, and you would be able to access the list.