3.1.6.7 Lists - more details

Lists - some simple programs

Now we want to show you some simple programs utilizing lists.
The first of them tries to find the greater value in the list. Look at the code in the editor.
The concept is rather simple - we temporarily assume that the first element is the largest one, and check the hypothesis against all the remaining elements in the list.
The code outputs 17 (as expected).

The code may be rewritten to make use of the newly introduced form of the for loop:
myList = [17, 3, 11, 5, 1, 9, 7, 15, 13] largest = myList[0] for i in myList: if i > largest: largest = i print(largest)
The program above performs one unnecessary comparison, when the first element is compared with itself, but this isn't a problem at all.
The code outputs 17, too (nothing unusual).

If you need to save computer power, you can use a slice:
myList = [17, 3, 11, 5, 1, 9, 7, 15, 13] largest = myList[0] for i in myList[1:]: if i > largest: largest = i print(largest)
The question is: which of these two actions consumes more computer resources - just one comparison, or slicing almost all of a list's elements?


myList = [17, 3, 11, 5, 1, 9, 7, 15, 13]
largest = myList[0]
for i in range(1, len(myList)):
if myList[i] > largest:
largest = myList[i]
print(largest)
  • Console 

Comments

Popular Posts