Listing
how to store lists of data in Python
Lists
We might call these arrays in other languages but in Python we call them lists:
Basically, the square brackets encapsulate the list and the commas separate the items!
Items
Lists can contain items of one or a mix of two or more types:
Lists can also contain zero items:
Adding to lists
When we already have a list with items, we can still add additional items with the append
method:
We call methods like append
"built-in" methods because the programming language supplies them without us having to write them!
Removing from lists
Just as easily as adding an item to a list, we can easily remove an item from a list using remove
:
Combining lists
We can combine, or concatenate, lists using the familiar +
operator:
Note that to add a single item using that syntax, we must put the single item to a one-item list:
Accessing items
To "get" items in a list, we use a syntax similar to arrays in other languages:
For this unfamiliar with zero-indexing, the first item of a list gets assigned an index of 0, while the second item an index of 1, and so on...
We can also use negative numbers to access a list from its end!
Modifying items
To change items in a list, we use an "access and assign" notation:
Removing items
To delete items from a list, we use the remove
built-in method by passing the value of the item(s) that we wish to remove:
Please note that if we have two or more identical values, using remove
will only delete the first instance:
As a side note, if we try to use remove
on an item that does not exist in the list, we will get an error!
Two-dimensional lists
Two-dimensional lists contain items that consists of lists (i.e. lists-in-a-list)!
Note that each item follows a pattern for the first item and for the second item!
Accessing two-dimensional lists
A very intuitive notation, the first set of square brackets refers to the larger list while the second set refers to smaller "list-in-a-list":
Modifying two-dimensional lists
Similar with one-dimensional lists, changing a two-dimensional list involves the "access and assign" notation, e.g. to modify John's age to 40:
Last updated