Till now, we have created a list and accessed individual elements of that list, now its time to learn how to use all of the elements in a list by iterating over them, using loops.
When you have a list with hundred or a thousand elements, and you want to access a few of them or all of them to perform some operation or calculation on them, it would be very hectic to use index numbers to access all the elements. In such cases, we use an iterative method, to iterate over all the list items. To understand how to iterate over list elements, we will be using loops. Don’t worry loops will be covered in details in Looping tutorial.
Introduction to Loops
Loops are used for doing redundant and repetitive tasks.
Using for
loop
Let’s start with for
loop. For iterating over a list, a for
loop will need two things – First, a reference variable to store the element being iterated and second, a source (list
or a range()
, as in the previous case). When a for
loop executes, elements of the source are one by one copied to the reference variable for utilizing(performing operations) them inside the loop. For example,
for x in range(0,5):
print (x)
0 1 2 3 4
In the above case, x
is our reference variable in which, each element in the range(0, 5)
is getting stored, iteratively(one by one), simple enough.
Also, you must know that range(0, 5)
returns a list
with elements 0 to 4 in it.
Using while
loop
Another way of iterating is by using the while
loop. The while
loop requires one condition to function. The loop keeps on iterating till that condition is true. As soon as it becomes false, the loops get terminated. For example,
i = 0
while i < 5:
print (i);
i = i+1;
0 1 2 3 4
You can see that both the loops returned the same output, but the while
loop, used the condition i < 5
in order to get the output. In simple english, it implies that “while i
is less than 5
, keep printing i
and keep incrementing the value of i
“. Do you know why we increment the value of i
, everytime after printing its value? Well, it’s because if we hadn’t incremented its value, the value would have remained the same as it was declared initially, which is, i = 0
, and the condition i < 5
, would have always been true and hence the loop would have never ended. Such condition leads to something that we call an infinite loop.
Using Loops with List
Enough about loops, now let’s see how we can use them to access the List elements. Take a list with any type of element. Now, using the for
loop we can access each element of the list very easily. For accessing the elements, we have to use a reference variable and our list variable as source.
myList = ['Last Of Us', 'Doom', 'Dota', 'Halo', ' ']
for x in myList:
print (x)
Last Of Us Doom Dota Halo
Iterate two Lists simultaneously – zip()
method
Suppose there are two lists and you want to ADD each element of the first list serially to each element of the second list and save it to a third (empty) list.
We can achieve this by executing a while
loop like shown in below code, but this is not the right way.
i = 0
A = [1, 2, 3, 4]
B = [5, 6, 7, 8]
C = []
while i < len(A):
C.append(A[i]+B[i]);
i=i+1
In the above code, we will have to add a lot of conditions to make sure that it runs without error all the time. For example, What if the size of both the list is not same?
We will have to do something different in such case because we have to iterate over the elements of two different lists, together. This can be done using the function zip()
.
Suppose the two lists are,
>>> A = [9, 8, 7, 6, 5] >>> B = [3, 4, 5, 6, 7]
Then, let’s create an empty list to save the results.
>>> C = []
Then the iteration process will require two reference variables, one for each list.
for x, y in zip(A, B):
C.append(x+y)
zip()
function can accept any number of list arguments. In this case, we have passed two lists A and B. Since both A and B have 5 elements, hence zip()
will make the loop iterate 5 times. But, what if both the lists have different number of elements? Suppose A have n
elements and B have m
elements, if m < n
then zip()
will make loop m
times, otherwise n
times.
Another approach to this problem could have been using the index number of the list A and B.
for i in range(0,5):
C.append(A[i]+B[i])
Although while using this technique it is necessary to know the size of both the lists prior to appending, while the previous approach (zip
function) can be used in almost any situation.