In the previous lesson, we used the read() method on the object my_file to get the full content of a file as one string.
Storing the foreign exchange rates as one string is not very convenient: we need to be able to handle rates individually.
This is where where the list data structure will come in handy.
A Python list is a collection data type that combines multiple values in one variable.
We can declare an empty list in two different ways.
lst1 = []
lst2 = list()
Lists can contain different types of data, like ints, floats, strings, or even other lists.
Initializing a list with a few strings is very natural.
currencies = ["GBP", "JPY", "CNY", "SEK"]
rates = [["EURUSD", 1.23], ["JPYGBP", 0.004747], ["USDJPY", 156.82]]
The built-in function len() returns the number of elements in the list.
If the list contains another list as an element, this still counts as one element, even if the list is empty.
print(len(currencies)) # 4
print(len(rates)) # 3
We can read individual elements from lists by using list index notation with squared parenthesis [ and ].
print(currencies[0]) # GBP
print(currencies[3]) # SEK
print(currencies[4]) # Error: index out of bounds
Indexing starts at zero: the first currency is currencies[0], and the fourth currency is currencies[3].
Negative list indexing can be used to start counting elements from the right.
Index -1 gives the last element of a list, -2 gives the second to last, et cetera.
print(currencies[-2]) # CNY
print(currencies[-4]) # GBP
print(currencies[-5]) # Error: index out of bounds
We can use indexation to update elements in the list.
currencies[-1] = "NOK"
print(currencies) # ["GBP", "JPY", "CNY", "NOK"]
We can join lists together using the + operator.
currencies = currencies + ["SEK", "INR"]
print(currencies) # ["GBP", "JPY", "CNY", "NOK", "SEK", "INR"]
Now let us return to our goal: extracting data from the file.
The file objects that we get from opening files have a method splitlines().
Where the read() method from the previous lesson returns the contents as one string, splitlines() returns a list of strings.
Each line will be a string element of the list.
For example, suppose that the file currencies.txt contains the following:
EUR
USD
NOK
HUF
Then the method splitlines() will return a list of four strings.
my_file = open("currencies.txt", "r")
contents = my_file.read()
my_file.close()
currencies = contents.splitlines()
print(currencies) # ['EUR', 'USD', 'NOK', 'HUF']