Mathematics, Sciences, and Technologies

Python for Scientists 1-5: Lists

,

Lists

The basic types of variables that have been introduced, such as integers, floats, and strings, are only individual instances. For example, we can define two different variables X == 3, and Y == 7.77, and they are independent of each other. However, almost all the time, we need to organize multiple variables into some structures for processing, layout, or facilitating manipulation. The most common of such a structure is a list, defined by square brackets []. The entries of the list will be separated by a comma ,. For example,

mylist = ["Apple", "Orange", "Banana", 67, 87.87, "on99"]
print(mylist)

will produce ['Apple', 'Orange', 'Banana', 67, 87.87, 'on99'] as expected.

Accessing Elements in Lists

To specify an entry in a list, we can use the syntax <list>[<index>]. Notice that the index in Python always starts from 0 instead of 1. E.g., to extract the third entry in a list, we shall write <list>[2]. Using the above example, if we write

print(mylist[0], mylist[2], mylist[5])

it will give Apple Banana on99. We can also count the elements backwards from the end by utilizing negative indices. <list>[-1] selects the last entry while <list>[-2] selects the second-to-last one. Again, using the same example, if we write

print(mylist[-1], mylist[-3])

it will yield on99 67.

We can also use slicing to select a range of elements. It has the form of start:end:step. Notice that the slice will not include end itself. For example, writing something along the lines of <list>[1:7:2] will extract the second, fourth, sixth entries (without the eighth entry that has the index of 7!) If step is not provided, then it will be assumed 1. Continuing our example, writing

print(mylist[1:5])
print(mylist[-1:-4:-2])

will return two lists ['Orange', 'Banana', 67, 87.87] and ['on99', 67] respectively. If start or end is left empty then it will automatically take the first or last index. So, if we write

print(mylist[2:])
print(mylist[:4:2])

the output will be ['Banana', 67, 87.87, 'on99'] and ['Apple', 'Banana'].

Modifying Elements in Lists

To update or change any element in a list is straightforward. We will just need to access the entries according to the above instruction and use the = equal sign symbol to assign the new value. For example,

mylist[-1] = "Hihi"
print(mylist)

now returns ['Apple', 'Orange', 'Banana', 67, 87.87, 'Hihi'].

Methods and Functions for Lists

Adding Elements into Lists

There are two ways to add elements into a list. The first one is by the method append which adds an element at the end of the list. For example,

mylist.append(114514)
print(mylist)

returns ['Apple', 'Orange', 'Banana', 67, 87.87, 'on99', 114514] (This assumes that we keep the same initial definition of mylist.) On the other hand, the method insert(<index>, <object>) can place the new element into the position we want. If we write

mylist.insert(1, 114514)
print(mylist)

it will now become ['Apple', 114514, 'Orange', 'Banana', 67, 87.87, 'on99'].

Removing Elements from Lists

Meanwhile, to remove a specific entry from a list, the most direct way is via del <list>[<index>]. A more standard way is by the pop(<index>) method. Note that this method will extract the removed element itself. This is demonstrated by

discarded = mylist.pop(3)
print(mylist)
print(discarded, "is removed.")

that outputs

['Apple', 'Orange', 'Banana', 87.87, 'on99']
67 is removed.

Another way to remove an element by its value, is to use the remove method. For example,

mylist.remove("Orange")
print(mylist)

returns ['Apple', 'Banana', 67, 87.87, 'on99'].

Combining Multiple Lists

A Pythonic way to combine two or more lists is to use the method <list_1>.extend(<list_2>). For instance,

cities = ["Tokyo", "Seoul", "Vancouver", "Paris"]
more_cities = ["Warsaw", "London", "Milan"]
cities.extend(more_cities)
print(cities)

prints ['Tokyo', 'Seoul', 'Vancouver', 'Paris', 'Warsaw', 'London', 'Milan']. Notice that the list cities is directly modified (in-place). Sometimes we may also choose to just use the simple + operator, which actually creates a new list object for that.

Enquiring the Length of Lists

To count the number of elements in a list, we simply use the len function: the value of len(mylist) should be 6.

Occurrence of Entries

On the other hand, to count the occurrence of a particular value, we may use the count method. For example,

some_nums = [1,2,1,2,3,5,3,3,5,1]
print(some_nums.count(1), some_nums.count(4))

returns 3 0. To find the corresponding index of a value, we can use the index method. Be aware that it only gives the index of the first occurrence: some_nums.index(3) should give 4.

Sorting Lists

There are two ways to sort a list. The first one is by using the function sorted and the second one is by using the method sort. Notice that the method approach will modify the list in-place but the function approach does not. To illustrate:

mylist_short = ["Apple", "Orange", "Banana", "on99"]
print(sorted(mylist_short))
print(mylist_short)
mylist_short.sort()
print(mylist_short)

will output

['Apple', 'Banana', 'Orange', 'on99']
['Apple', 'Orange', 'Banana', 'on99']
['Apple', 'Banana', 'Orange', 'on99']

Notice that capitalization matters. It is very common to wrongly expect that 'on99' would come before 'Orange' but that is not true. Readers can search about “ASCII” to understand why.

We may also achieve reversed sorting by supplying the parameter reverse. For example, print(sorted(mylist_short,reverse=True)) should produce ['on99', 'Orange', 'Banana', 'Apple']. We will talk about what True (or False) is later.

Exercise

Given the following two lists:

Entente = ["United Kingdom", "France", "Russia", "Italy"]
Central = ["German Empire", "Austria-Hungary", "Ottoman Empire", "Bulgaria"]

Sort the two lists individually then combine them together, versus combine the two initial lists first and then sort the resulting list. What if we further append 1914 to the new list and sort again?

Suggested Solution

The first one may be done via

Entente_sorted = sorted(Entente)
Central_sorted = sorted(Central)
print(Entente_sorted + Central_sorted)

that gives ['France', 'Italy', 'Russia', 'United Kingdom', 'Austria-Hungary', 'Bulgaria', 'German Empire', 'Ottoman Empire']. Meanwhile, the second one may be done by

combined = Entente+Central
combined.sort()
print(combined)

that yields ['Austria-Hungary', 'Bulgaria', 'France', 'German Empire', 'Italy', 'Ottoman Empire', 'Russia', 'United Kingdom']. (There are many possible ways to do these.) If 1914 is appended as a string and we write something like

combined.append("1914")
combined.sort()

then it should now be placed at the beginning of the list, i.e. ['1914', 'Austria-Hungary', 'Bulgaria', 'France', 'German Empire', 'Italy', 'Ottoman Empire', 'Russia', 'United Kingdom']. Otherwise, if 1914 is appended as a number without quotation marks, then an error will arise, because strings and numbers cannot be compared directly.

Leave a Reply

I’m Benjamin

Welcome to my Mathematical World! Here you can find posts and tutorials related to applied topics like Linear Algebra, Calculus, Differential Equations, and Programming. Feel free to leave comments and suggestions!

Discover more from Benjamin's Maths World

Subscribe now to keep reading and get access to the full archive.

Continue reading