Ordered Collections - Sequence
Python provides three data structures for ordered collection, also called sequence; Lists, Tuples and Ranges.
In this lesson we will learn all three.
Lists are used for representing ordered collection of mutable objects - both compound and primitive. Here is an example of a collection of numbers called scores.
scores = [50, 80, 90, 100]
Notice the square bracket used to represent the collection. A list can also be created by using list function and passing in any iterable object. In this case the above statement would be
mylist = [50, 80, 90, 100] scores = list(mylist)
Although note that you may not see a specific advantage in using the list function in this example as you are passing in a list object to the list function, but remember list function can be applied to any iterable object from sequence or collection like tuples, dictionaries, set etc., which you will learn next.
Here are some of the commonly used operations on lists:
|Positive positional index||scores||50||first position in the list has a value:50|
|Negative positional index||scores[-1]||100||first position from the end.|
|Slicing||scores[0:2]||[50, 80]||new list with numbers from position 0 (included) to 2 (excluded)|
|Slicing with start position default||scores[:2]||[50, 80]||new list with numbers from from 0 index and 2nd position (excluded)|
|Slicing with end position default||scores[2:]||[90, 100]||new list with numbers from position 2 to end of the list|
|Build in function len||len(scores)||4||len can be applied to lists to obtain the size of the list|
|Modify an element|| |
scores = 60
[60, 80, 90, 100]
|lists can be modified unlike strings|
|Add new element|| |
[60, 80, 90, 100, 90]
|adds a new element at the end of the list|
|Use slice to replace more than one element|| |
[60, 80, 89, 99, 90]
|numbers in 2nd and 3 positions are replaced|
|Use slice to remove all elements|| |
|||removes all elements of the list!|
|Use slice with a step value||scores[:4:2]||[60, 89]||step value '2', gets elements in increment of the step value|
|Use slice with a step value||scores[::-1]||[90, 99, 89, 80, 60]||using -1 as step value reverses the list.|
|List of lists|| |
scores = [50, 60]
[[50, 60], ['joe', 'john']]
|term is a list of lists|
|Sort a list in place|| |
scores = [60, 30, 80]
[30, 60, 80]
|scores is sorted in place using the default sort algorithm - sort from smallest to largest. Can change the default by passing in optional 'key' and 'reverse' attributes to sort function.|
Few other useful methods: There are a few other interesting methods on lists. Replace 'list' below with the name of your list.
- list.count(x) - returns the number of times number x appears in the list
- list.index(x[, start[,end]]) - return index value of the first item whose value is x. Raises ValueError if no such item. Optional start and end are used to limit the search similar to slice.
- list.insert(index,element) - to insert the specified element at the specified index
- list.remove(element) - to remove the given element from the list
- list.pop([index]) - removes the last element if no index is specified, otherwise it gets the specified index element and removes it from the list.
Although a few methods are described above, there are many more methods you can use and the best way to figure out the available methods is to use the code complete prompts that show up when you use the dot operator on any object in most of the IDE's including Colab. By clicking on the Read more icon on the prompt, you can view the full documentation of that function also.
Here is what you see in Colab:
You can apply several built-in functions on the list structures. In the first lesson you calculated mean of 3 individual numbers. If you create a list object of the same three numbers, then you can use the sum function on the list to calculate the sum of all the list numbers and use len function to calculate the total number of elements in the list. Then the mean of all the numbers in the list can be obtained as shown below:
my_numbers = [15, 35, 55] mean = sum(my_numbers) / len(my_numbers) print(mean)
You can also apply sorted built in function on any list. This will return a sorted list and the original list is untouched. This is different from the sort function which can be applied on a list, which sorts the list in place. The default sort order is small to large. You can change this default sort order by passing in the 'key' and 'reverse' attributes to the sorted function. More on this: https://docs.python.org/3/howto/sorting.html
Complete list of built-in functions can be found at: https://docs.python.org/3/library/functions.html
You can also construct a list with each element being of a different data type. Here is an example:
a = ['John', 30, True]
In this list, the first element is a string and the second an integer and the third is a boolean. Collection of items is a mix of String, number and boolean, and so the term heterogeneous,