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

A list is used to represent a collection of objects that is kept in an order. 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:

Operations Example Output Comments
Positive positional index scores[0] 50 first position in the list has a value:50
Negative positional index scores[-1] 100 first position from the end.
similarly -2 will get second element from last and so on.
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
Slicing with negative index 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[0] = 60
print(scores)
[60, 80, 90, 100]
lists can be modified unlike strings
Add new element
scores.append(90)
print(scores)
[60, 80, 90, 100, 90]
adds a new element at the end of the list
Use slice to replace more than one element
scores[2:4] = [89, 99]
print(scores)
[60, 80, 89, 99, 90]
numbers in 2nd and 3 positions are replaced
Use slice to remove all elements
scores[:] = [ ]
print(scores)
[] 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
Reverse using -1 as step scores[::-1] [90, 99, 89, 80, 60] using -1 as step value returns a new list with elements reversed.
Reverse using reverse method scores.reverse() [90, 99, 89, 80, 60] reverses the elements in the existing list.
List of lists
scores = [50, 60]
names = ['joe', 'john']
term = [scores, names]
print(term)
[[50, 60], ['joe', 'john']]
term is a list of lists
Sort a list in place
scores = [60, 30, 80]
scores.sort()
print(scores)
[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 'reverse = True' attributes to sort function.
Get a new list sorted
scores = [60, 30, 80]
result = sorted(scores)
print(result)
[30, 60, 80]
Same as sort except you get a new sorted list instead of existing list being sorted.
Concatenate lists
scores = [10] + [2, 3] + [11, 15]
print(scores)
[10, 2, 3, 11, 15]
Multiple lists are added together

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.
  • list1.extend([list2]) - adds all elements of list2 into list1.

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:

Built-in functions

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)

Output:

35

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

Official reference

Complete list of built-in functions can be found at: https://docs.python.org/3/library/functions.html

Heterogeneous List

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,

results matching ""

    No results matching ""