Lists and arrays
A list is a way to store multiple values together under a single identifier. You may see the term list interchanged with the term array. Technically, an array must contain all
values of the same data type but a list is able to hold values of different data types. Python actually only has a list function which we use for both lists and arrays.
Declaring a list
The same rules apply to list identifiers as to variable identifiers. Some example lists and arrays are shown below.
team = ["Bob","Ben","Bill"] scores = [17,25,21,23] user = ["Bob",17,True] |
list declaration syntax rules:
- An appropriate identifier is created to store the list under
- The entire list is surrounded by square brackets
- Items in the list are separated by commas
- Data in the lists follows the rules for its data type i.e. strings have speech marks around them and other data types do not
Accessing items from a list
To access items from a list we use the list identifier and the position of the item we wish to access from the list in square brackets. Lists use 0 indexing meaning the first item in a list is in
position zero and the second item is in position one etc.
list access syntax rules:
- You use the lists identifier
- The identifier is followed by square brackets
- The position of the item in the list you want to access is given as an integers
This can also be used to assign a new value to an item in a list. This only works to give an existing list item a new value not to declare an additional item in the array.
team = ["Bob","Ben","Bill"] team[1] = "Jim" print(team) |
The code above would print out the updated team list: ["Bob","Jim","Bill"]
Appending to a list
Appending to a list means adding an additional value to the end of a list. To append to a list, we declare the identifier of the list and use dot notation to append as shown below.
This would add "Fred" onto the end of our team list which last contained ["Bob","Jim","Bill"] so the new list would be ["Bob","Jim","Bill","Fred"].
Removing a specific value from a list
If you know the value of an item you wish to remove you can use the dot remove notation to perform this action. If you pass a value that occurs more than once in the array then only the
first instance of that value will be removed from the array.
nums = [1,2,2,3,5,8] nums.remove(2) |
The above code would remove the first 2 from the list nums leaving it as [1,2,3,5,8]
Removing an item from a specific position in a list
Using the pop method
The dot pop command can be used to either, remove the last item of a list if no parameter is passed, or remove the value in the specified position if a parameter is passed. The pop command
also returns the removed value so you can use it elsewhere.
names = ["Ben","Bob","Don","Jim","Sam"] last_name = names.pop( ) second_name = names.pop(1) |
The code above would remove "Sam" from the list and store "Sam" in the variable last_name. Then it would remove "Bob" and store it in second_name. At the end of the code the names list now contains
["Ben","Don","Jim"]
Using the del method
When you don't need to return the value you remove to use elsewhere the del command may be a better choice to delete a specific item from the array.
names = ["Ben","Bob","Don","Jim","Sam"] del names[3] |
The code above would delete the item in position 3 from the list which is "Jim", leaving the list as ["Ben","Bob","Don","Sam"]
Clearing a list
If you have need to wipe out the data in a list and start over, you can do this with the dot clear command as seen below.
names = ["Ben","Bob","Don","Jim","Sam"] names.clear( ) |
This would leave an empty list called names.
Sorting a lst
If a list contains all strings or all numeric values then you can use the .sort command to sort the list numerically or alphabetically.
names = ["Jim","Don","Sam","Ben","Bob"] names.sort( ) print(names) |
The output from the code above would be ["Ben","Bob","Don","Jim","Sam"] because .sort() tells it to sort the list alphabetically. If you change it to names.sort(reverse = True) then it will be in reverse
alphabetical order. The same can be applied to numerical data types where the default for sort is ascending order and adding reverse = True causes descending order to be applied.
Syntax checker
Fix the code below to achieve the requested outcome.
names = ["Ben","Bob","Don","Jim","Sam"] |
names.append("Tim") # changed to append command |
names.remove("Jim") # the remove command needs a value not a position as input |
first = names.pop(0) # with no number pop will return the last value not the first |
print(f"{first} is first in the queue") |
del names[1] # the 2nd name in the names list is in position 1 not 2 |
Two dimensional lists
A two-dimensional list is a list where each element in the list is another list.
Declaring a two-dimensional array
Imagine you had an array that held test scores for each student in a class. Each of these students has completed several tests. The list to store this data may look like below.
scores = [[15,19,22],[25,21,23],[7,12,9],[15,18,12]] |
The above code defines a list with data for 4 students shown in each of the lists inside the main list. Each student then has results recorded for 3 tests.
2D list declaring syntax rules:
- An appropriate identifier is created to store the list under
- The entire list is surrounded by square brackets
- The lists in the main list are separated by commas
- Each sub-list also uses square brackets
- Data in the lists follows the rules for its data type i.e. strings have speech marks around
them and other data types do not
Accessing items from a 2D list
To access data from a two-dimensional list we specify two values each in square brackets. The first value specifies the sub-list to look in and the second value specifies the position within that
sub-list as seen below.
2D list access syntax rules:
- You use the lists identifier
- The identifier is followed by two sets of square brackets
- The position of the list to be used and the item in the list you want to access are given as an integers
Appending to a 2D list
To append an additional list to our list of lists, we declare the identifier of the list and use dot notation to append as shown below.
scores.append([13,17,15])] |
This would add a new array [13,17,15] onto the end of our scores list which last contained [[15,19,22],[25,21,23],[7,12,9],[15,18,12]] so the new list would be [[15,19,22],[25,21,23],[7,12,9],[15,18,12],[13,17,15]]
To append an additional value to one of the lists in our list of lists, we declare the identifier of the list and the sub-list to us then use dot notation to append as shown below.
This would add a new value to the second sub-list which last contained [25,21,23] so the new list would be [25,21,23,20].
Removing a specific value from a list
If you want to remove a whole sub-list then the whole sub-list would need to be passed as a parameter. You can remove individual items from sub-lists by specifying the sub-list before using dot remove.
scores = [[15,19,22],[25,21,23],[7,12,9],[15,18,12]] scores.remove([15,19,22]) scores[1].remove(7) |
The code above would first remove the first sub-list. Next it looks in what is now the second sub-list and removes 7 leaving the scores list as [[25,21,23],[12,9],[15,18,12]].
Removing an item from a specific position in a 2D list
Using the pop method
The pop command takes only one parameter. Using it with no value passed will pop the final sub-list and return it. Using it with a parameter will pop the specified list and return it. To use pop to return
values from within a sub-list you need to specify the sub-list. Again, without a variable, the last value is returned and with one the specified value is popped and returned.
scores = [[15,19,22],[25,21,23],[7,12,9],[15,18,12]] print(scores.pop()) print(scores.pop(1)) print(scores[1].pop()) print(scores[1].pop(1)) |
The code above would first remove and print the sub-list [15,18,12]. Next it removes and prints the list in position 1 i.e. the second sub-list [25,21,23]. Next, we specify the sub-list in position 1 i.e.
the second sub-list in our main list that now only has two remaining sub-lists. Pop without a parameter would remove and return the last value in this sub-list 9 and pop with a parameter of 1 removes the item in
position one in that sub-list which is 12. The scores list after all commands would be [[15,19,22],[7]]
Using the del method
The del command can take either one or two parameters to delete either an entire sub-list or a specified value in a sublist.
scores = [[15,19,22],[25,21,23],[7,12,9],[15,18,12]] del scores[1] del scores[0][2] |
The code above would first delete the entire sub-list in position 1 i.e. the second sub-list. The second delete command would look in the first sub-list and remove the item in position 2 i.e. the third item.
Clearing a 2D list
Using dot clear on a two-dimensional list will remove all sub-lists leaving just an empty one-dimensional list. If you specify the sub-list you can just clear a sub-list.
scores = [[15,19,22],[25,21,23],[7,12,9],[15,18,12]] scores[1].clear() scores.clear() |
The first command here would clear the sub-list in position 1 i.e. the second sub-list. This would leave the scores list as [[15,19,22],[],[7,12,9],[15,18,12]]. The second clear command would leave an empty
one-dimensional list.
Lambda sorting
Lambda sorting can allow us to sort a 2D list based on the value in a certain position in each sub-list.
scores = [[15,19,22],[25,21,23],[7,12,9],[15,18,12]] scores.sort(key=lambda x:x[1]) print(scores) |
The code above would print [[7,12,9],[15,18,12],[15,19,22],[25,21,23]] because the code instructs it to sort the list of sub-lists based on the value in position 1 in each sub-list i.e. the 2nd score. By default .sort()
will sort based on the first element in each sublist. Change the number in the square brackets to change which item in the sub-lists you sort on. By default it places the sublists in ascending order of the specified value
but you can also apply reverse = True so that scores.sort(reverse=True, key=lambda x:x[1]) would put them in descending order in terms of their second value.
Syntax checker
Fix the code below to achieve the requested outcome.
scores = [[15,19,22],[25,21,23],[7,12,9],[15,18,12]] |
scores.append([13,17,8]) # fixed append command |
for score in scores: |
score.append(25) # appends to each score not the scores array |
for score in scores: |
del score[0] # fixed application of del command |
print(scores.pop(1)) # fixed parameter to pop second sublist not third |