Python gives you arrays with Jjsts

Sometimes, different programming languages have different names for roughly the same thing. For example, in Python most programmers think array when they are actually using a Python list. For our purposes, think of Python lists and arrays as the essentially same thing.

You create an array in Python like this.

array a name-

Python coders typically use the word array to more correctly refer to a list that contains only data of one type, like a bunch °f strmy a bunch of numbers. And Python comes wW» a built-in technology called "array" for jst that purpose-However, as lists are very similar and much more flexible, we prefer to use them, so you dont need to worry about this distincW for now-

Assign a list of values to it-

Assign a list of values to it-

This creates a two-item array and gives it the name my wo To look at individual items in the array, index the element required.

You can read individual pieces of data from inside the array using an index, just like you read individual characters from inside a string.

As with strings, the index for the first piece of data is 0. The second piece has index 1, and so on.

Arrays can be extended

But what if you need to add some extra information to an array? Like strings, arrays come with a bunch of built-in methods. Use the append () method to add an extra element onto the end of the array.

>>> my_words.append("Bettys") >>> print(my_words[2]) Bettys

The avvay has gy-own by one data element-

Rewrite your program so that each time you read a new score you append it to the end of an array called scores.

Then amend the code to print out the first 3 scores in the list.

Here's the code as it currently stands highest_score = 0

result_f = open("results.txt")

for line in result_f:

(name, score) = line.split() if float(score) > highest_score: highest_score = float(score) result_f.close() print("The highest score was:") print(highest_score)

Hint: To create an empty array of scores use scores = [].

high scores in the array

Here's the code as it currently stands.

You were to rewrite the program so that each time you read a new score you append it to the end of an array called scores.

You were then to amend the code to print out the first 3 scores in the list.

highest_score = 0

result_f = open("results.txt")

for line in result_f:

(name, score) = line.split() if float(score) > highest_score: highest_score = float(score) result_f.close() print("The highest score was:") print(highest_score)

Start with an empty array.

., , . result f = open(llresultst*t") Process the data in

the file as before..^ for line in result_f:

...but, this time, append the . scores.append(float(score)) scores to an array.

result_fclose()

print("The top scores were:")

print(scoresC03)

With the data safely . prmt(scoresCI3) stored in the array, pmt out the first 3 print(scoresC23) array elements.

Was this article helpful?

0 0

Post a comment