Lists¶
So far, we have mentioned tuple and range as types of collections, and we have seen that the string can also be used as a collection. Another very important and often used type of collections are lists.
Lists and tuples¶
Lists, as well as tuples, can be specified by enumerating the elements, except that the list elements are written between square brackets:
The lists are in many ways similar to tuples. All of the features of the tuples mentioned in the collections chapter apply to lists as well:
A list can also be placed in a variable and vice versa - list elements can be assigned to an appropriate number of variables (in other words, a list can be packed and unpacked)
list elements can be accessed using the list name and the sequence number (index) of the element written in square brackets
list length is obtained by the function len
The lists also have some features that set them apart from the Tuesdays. For example, lists can be extended using the append function:
Also, list elements can change their values and can be deleted from the list:
Such operations with tuples are not possible. Once made, the tuple remains as it is. A tuple cannot be modified - it cannot change its length or the values of individual elements. A variable containing a tuple can only get a whole new tuple as a value, but thus the previous tuple was not modified but ceased to exist. That is why tuples are said to be immutable.
Tuples can be used for collections of data that we do not intend to modify while executing a program (we can change them manually before executing a program). In this way, we ensure that the data will not change accidentally, and program will work slightly more efficiently with the tuple than it would do with the list.
Tuple t can be converted to a list a during the program execution, and vice versa: a = list (t)
or t = tuple (a)
, but such conversions are seldom needed and better avoid them (if they are often applied to large collections, conversions like this can slow the program significantly).
Building a list¶
We can gradually build lists in a program. For example, if we are given a tuple of numbers from which we want to copy those that are greater than zero (and perform some extra task with these numbers latter), we can do this:
At the beginning we have an empty list, and then in the loop we use the append function to add to the list the elements we want.
Loading a list¶
In the same way, we can load data into a list:
Another way to load a list is to first form a list of required length and then assign the loaded values directly to the list elements in the loop.
We used the statement a = [0] * n
to form a list of n elements. The operation [0] * n
is called list multiplication. The result of the list multiplication is concatenation of n repetitions of the given list. For example, [0] * 5 is the list [0, 0, 0, 0, 0], and [2, 7] * 3 is the list [2, 7, 2, 7, 2, 7].
If the user enters all the elements of the list in one line separated by spaces, we write the program like this:
We used the split() function to parse the entered text into shorter strings containing individual numbers.
split() function:
The split() function parameter is a character or text that we want to use as a separator. If a separator is not specified, a space ‘ ‘ is assumed as default.
"1234 56".split() -> ["1234", "56"]
"1234,6".split(',') -> ["1234", "56"]
The result of the split() function is a string list. The number of shorter strings we get as a result depends on the number and layout of the separator characters in the argument string. For example, if the text contains only one separator somewhere in the middle, we will get two shorter strings. Each new appearance of the separator character can produce one string more in the resulting list (if it really separates some part of the starting string from the rest of the text).
"1;23;456;7".split(';') -> ["1", "23", "456", "7"]
" 1 234 56 7 ".split() -> ["1", "234", "56", "7"]
Examples and tasks¶
Example - sales
At the beginning of the script, the values of several sales in one store are given. Extract the sales with a value greater than 1000 and less than or equal to 4000 into a list, then print the list elements out.
The problem is solved as follows:
Example - Leap changes
A tuple of numbers is given. Extract numbers that differ from their predecessors at least by 10, then print them out.
One possible solution is:
Task - even numbers
A tuple of numbers is given. Extract the numbers that are even and then print them out.
Recall that the number x is even if \(x \% 2 == 0\)
Task - every third word
A tuple of strings is given. Extract strings whose indices are divisible by 3, then print them.
Task - below zero
A tuple of numbers is given. Extract the numbers that are negative and their predecessors are positive, then print the separated numbers.