flowchart LR
subgraph memory
actg
""
end
subgraph variables
dna
end
dna --> actg
Lists
Resources
- Lists and tuples in the official documentation, and more on lists.
- A Real Python introduction to lists.
- lists on the Python google course (available in different languages).
Lists
So far we have seen basic, or scalar, types like: int, float, str, bool and None. List is a compound type, a type capable of holding different items.
Lists can hold any kind of type, not just basic types, but also compound types, like another list.
It is quite common to use lists to represent vectors, lists of numbers, and lists of lists to represent 2d-arrays, matrices.
Lists can be heterogeneous, they can hold inside elements of different types.
In Python there is another type, very similar to a list, but that is limited to have all its elements of the same type, the array. Arrays are more efficient than lists, but in most cases the difference is not noticeable and lists are just fine.
List creation with list
As we have seen lists can be created using square brackets ([]). But lists can also be created using the list function. This function takes any iterable and returns a list. (An iterable is an object capable of returning its members one at a time). For instance we can create a list of letters using list.
Lists are sequences
Lists are sequences. A sequence is an object composed by items that can be accessed using indexes and that has a length, the number of items that holds. We have already seen another sequence type, the string.
Number of items, length
Indexing
Lists items can be accessed using indexes, exactly like strings were accessed.
You have to be careful. When the index is just one number you will get one item, but if the index is a slice you will always get a list, even if you are selecting just one item.
Predict the result of running the following code:
Create a list with the numbers from 0 to 9, extract the odd and even numbers, the first 5 and the last 5.
sorting
Lists can be sorted using the sorted function.
sorted does the sorting doing pairwise comparisons of the elements. For a list of numbers the result is what we could expect.
For for the letters, or many other kinds of objects, the result can be weird.
The sorted function has a parameter, key, that allows to modify the elements compared. key will be a function that takes one element and returns the element to be compared. This is a topic somewhat more advanced, but you have an excellent sorting tutorial in the official documentation.
Sort the words in alphabetical order.
The sorted function creates a new list, the original list will be intact.
If you wanted to sort the original list in place you could use the sort method.
Fix the following code:
The sort method sorts the list in place and it does not return the list.
reverse
As we did with strings, we can also reverse a list, or any other sequence, using the function reversed. reversed returns an iterator, so in order to have a list we need to use the list function on the reversed result.
min, max and sum
Python has some useful functions for numeric sequences and iterators like min, max and sum.
There are more basic statistics functions in the statistics module of the starndard library, and if you are interested in data analysis you will have to learn about numpy, pandas, and the rest of the libraries that conform the data analysis ecosystem.
Multiple assignment
Lists, and tuples, can be used to assign its values to different variables.
This is a feature commonly used in Python that, sometimes, is known as destructuring assignment. These assignments will fail if the number of items at both sides are different.
list operators
concatenate with +
Two lists can be concatenated into a new list by using the + operator.
in operator and index method
We can check if an item is in a list with the in operator.
If you need the position of the element in the list you can use the list index method.
If the item is found several times in the list, you will only get the index of the first appareance.
If you try to locate the position of an element that is not in the list, you will get an error.
Lists are mutable
Strings were inmutable sequences, once you create a string, it can not be changed. You can obtain a new modified string, for instance an uppercase string, but the original string will be unmodified.
You might have though that the original string was lost because most of the time we were reusing the name of the variable.
But what is going one in this code is more subtle:
- dna = “atcg” creates, and stores in memory, the string “atcg” and assigns the dna varible as a reference to it.
- dna.upper() creates a new string “ATCG”
flowchart LR
subgraph memory
actg
ACTG
end
subgraph variables
dna
end
dna --> actg
- dna = dna.upper() assings the dna variable to the new string “ATCG”
flowchart LR
subgraph memory
actg
ACTG
end
subgraph variables
dna
end
dna --> ACTG
- There is now no variable referencing to the original “actg” string, so even if it would still be in memory it would be inaccessible to us.
- At some point the Python interpreter will remove the original “actg” string from memory because it is not referenced by any variable, but this is of no concern to us. (This process is known in computer science as garbage collection, and Python is a garbage collected language).
Lists, on the other hand, are mutable. As an example, let’s use the append method, that appends a item to the list.
flowchart LR
subgraph memory
list[G, C, A, T]
end
subgraph variables
dna
dna2
end
dna --> list
dna2 --> list
As you can see the variables dna and dna2 refer to the same list in memory, so when we change that list, in this case by sorting it, both variables print the same result. It is worth mentioning that the sort method, unlike the string methods or the sorted function, does not return a new list.
append and extend
The append method adds an element to the list.
The extend method adds any number of elements to the list, it takes any iterable.
Predict the result of running the following code:
What would happend if you try to append a list of numbers? Try it, and explain the result.
append adds one item to the list and, in this case, this element happens to be the list [4, 5, 42], so no problem, we end up with a list that has this element in it.
Modify the list using indexes
Lists can also be changed by using the indexing syntax.
Predict the result of running the following code and think about why the two methods yield different results.
tuples
In Python there is another type, very similar to a list, but inmutable, the tuple. We create tuples using parentheses instead of square brackets.
If you try to modify a tuple, you will get an error.
Python tuples have a gotcha. They are created using parentheses, but if you want to create a tuple with just one element you need to include a trailing comma.
Empty lists or tuples are false
Create an empty list and an empty tuple and trasnform it into a boolean (type cast it into a boolean). Create also a list and a tuple with one element and type cast it to boolean.
More methods, help
The functionallity offered by the list and tuple types is very rich, if you want to explore it in more detail remember the official documentation and the help function.
More exercises
Split the items separated by commas into a into a list and transform each item in a number.
We want to store the name, surname and grades of a student into three variables, and we want to calculate the mean grade.
Carry out the following manipulations.