|
Manipulating ListsThere are a number of ways to manipulate lists in Python. The following table describes them:
You can use + to join two lists together:
You can use append to add a value to the end of a list:
To delete a value from a list, use del, which expects the index of the list value it is deleting:
If you know what element you want to delete, but do not know where in the list it is, use remove:
To reverse the order of a list, use reverse:
sort sorts a list of numbers in numeric order, or a list of strings in alphabetical order:
len returns the number of values in a list:
index locates an item in a list, and returns its index:
In this example, index finds the first occurrence of the string Admitted in the list. Since this is the third element of the list, statusindex is assigned 2. (Recall that indexing always starts from zero.) pop removes an item from a list, specified by index, and allows you to assign it to another variable:
If you do not specify an index, pop removes the last element of the list and assigns it:
|