Traversing a list is a useful tool that can be used to see the list elements (using the print function) or to update list element values. The most common way is to apply the for loop to traverse over list elements.
Example 1 Create a list with numbers from 0 to 10 (including 10), traverse over list elements and print each element of the list.
Solution: To create a list with specified elements type in the following.
Solution:For this example we will create a simple list containing numbers from 0 to 10 (including 10).
Example 1 Create a list with numbers from 0 to 10 (including 10), traverse over list elements and print each element of the list.
Solution: To create a list with specified elements type in the following.
listA = [i for i in range(0,11,1)]This will create a list with a length of 11 containing numbers from 0 to 10 (including 10). To traverse over list elements and show each list element using the print function we will use for the loop. The following code will as an output show each list element.
for i in range(len(listA)):The previous code will as an output show every element of the listA.
print("listA[{}] = {}".format(i, listA[i]))
listA[0] = 0In the following example, we will update the value of each list element i.e. calculate the power of 2 for each list element. Example 2 Update the value of each list element by calculating the power of 2. To do that perform traversing using for loop.
listA[1] = 1
listA[2] = 2
listA[3] = 3
listA[4] = 4
listA[5] = 5
listA[6] = 6
listA[7] = 7
listA[8] = 8
listA[9] = 9
listA[10] = 10
Solution:For this example we will create a simple list containing numbers from 0 to 10 (including 10).
listA = [i for i in range(0,11,1)]Now we will be using for loop update each value of the list element by calculating the power of 2 of each element. This will be achieved using for loop.
for i in range(len(listA)):The second line in the previous code block will in each iteration calculate the power of 2 of each existing list element and update the existing value of the list element with a new one. To show the updated version of listA we will again transverse over a list using for loop.
listA[i] = listA[i]**2
for i in range(len(listA)):The previous code will generate the following output.
print("listA[{}] = {}".format(i, listA[i]))
listA[0] = 0
listA[1] = 1
listA[2] = 4
listA[3] = 9
listA[4] = 16
listA[5] = 25
listA[6] = 36
listA[7] = 49
listA[8] = 64
listA[9] = 81
listA[10] = 100