3.1.4.10 Lists - collections of data | lists and loops

Making use of lists

The for loop has a very special variant that can process lists very effectively - let's take a look at that.
Let's assume that you want to calculate the sum of all the values stored in the myList list.
You need a variable whose sum will be stored and initially assigned a value of 0 - its name will be total. (Note: we're not going to name it sum as Python uses the same name for one of its built-in functions - sum(). Using the same name would generally be considered a bad practice.) Then you add to it all the elements of the list using the for loop. Take a look at the snippet in the editor.
Let's comment on this example:
  • the list is assigned a sequence of five integer values;
  • the i variable takes the values 0123, and 4, and then it indexes the list, selecting the subsequent elements: the first, second, third, fourth and fifth;
  • each of these elements is added together by the += operator to the total variable, giving the final result at the end of the loop;
  • note the way in which the len() function has been employed - it makes the code independent of any possible changes in the list's content.

The second face of the for loop

But the for loop can do much more. It can hide all the actions connected to the list's indexing, and deliver all the list's elements in a handy way.
This modified snippet shows how it works:
myList = [10, 1, 8, 3, 5] total = 0 for i in myList: total += i print(total)
What happens here?
  • the for instruction specifies the variable used to browse the list (ihere) followed by the in keyword and the name of the list being processed (myList here)
  • the i variable is assigned the values of all the subsequent list's elements, and the process occurs as many times as there are elements in the list;
  • this means that you use the i variable as a copy of the elements' values, and you don't need to use indices;
  • the len() function is not needed here, either.


myList = [10, 1, 8, 3, 5]
total = 0
for i in range(len(myList)):
total += myList[i]
print(total)
  • Console 

Comments

Popular Posts