Lesson
Python Lists
Lists are an important data type that allows you to keep a set of iterable item(s). Lists are mutable sequences. This literally means you can have a list of items, like 1, 2, 3 or "h", "e", "l", "l", "o", "!". A list is denoted by square brackets, [] . To create a list that holds actual items, you'll need to put them within the square brackets and you may need to use commas to separate the items.
>>> []
[]
>>> [1]
[1]
>>> [1, 2, 3, 4 ,5]
[1, 2, 3, 4, 5]
>>> ["h", "e", "l", "l" ,"o", "!"]
['h', 'e', 'l', 'l', 'o', '!']
>>> [1, 102, 2.22, "F", 2/2, 1+2j, False]
[1, 102, 2.22, 'F', 1.0, (1+2j), False]
>>> list("hello")
['h', 'e', 'l', 'l', 'o']
As you can see, the built-in function, list() converts a non-list into a list, although this will be discussed later on. List can also hold multiple different data types, so you can mix numbers, strings, and complexes. Better yet, we can nest lists within each other.
>>> [[1, 2, 3], [2, 1, 3], [True, False, True]]
[[1, 2, 3], [2, 1, 3], [True, False, True]]
>>> [[[[[[1, 2, 3]]]]]]
[[[[[[1, 2, 3]]]]]]
>>> [[[[ 1, 2, [[1, 2, 3]]]]]]
[[[[1, 2, [[1, 2, 3]]]]]]
List nesting can get very complicated as the nesting gets deeper, but it creates a great amount of power that will be harnessed in the later parts of this course.
List Indexing
Like strings, list can be indexed. Indexing can be used to get one item out of the list. For example, if you want to get "o" out of ["h", "e", "l", "l", "o", "!"] you'll need to type ["h", "e", "l", "l", "o", "!"][4] although, for brevity, we'll put the lists in a variable first. Don't forget that indexing is zero-based in Python.
>>> spam = ["h", "e", "l", "l", "o", "!"]
>>> spam[1]
'e'
>>> spam[5]
'!'
>>> spam[3]
'l'
Like strings, you can index starting with the last items by using a negative number. Don't forget that negative one is the start of the last item, not zero!
>>> spam[-1]
'!'
>>> spam[-3]
'l'
>>> spam[-2]
'o'
>>> spam[-5]
'e'
If you index out of range, by trying to get an item that doesn't exist, you'll get an IndexError .
>>> spam[1000]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> spam[-10]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
List Slicing
Like strings, lists can be sliced. When you slice a list, it will return a new sliced copy of the original list.
>>> spam = [1, 2, 3]
>>> spam[0:3]
[1, 2, 3]
>>> spam[0:]
[1, 2, 3]
>>> spam[1:]
[2, 3]
>>> spam[:1]
[1]
>>> spam[:-1]
[1, 2]
>>> spam[:0]
[]
Lists also supported extended slicing, where the third parameter acts as the "step". A step of 1 is the default value.
>>> bacon = ["h", "e", "l", "l", "o", ",", " ", "w", "o", "r", "l", "d", "!"]
>>> bacon[::-1]
['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'h']
>>> bacon[::1]
['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!']
>>> bacon[::2]
['h', 'l', 'o', ' ', 'o', 'l', '!']
>>> bacon[::-2]
['!', 'l', 'o', ' ', 'o', 'l', 'h']
>>> bacon[::-5]
['!', 'w', 'l']
>>> bacon[:7:-2]
['!', 'l', 'o']
List manipulation
Adding a new item to a list is pretty basic. The best way add a new item is by using the built-in list function append() . This can be easily do as shown below.
>>> spam = [1, 2, 3, 4]
>>> spam.append(5)
>>> spam
[1, 2, 3, 4, 5]
>>> spam.append(12)
>>> spam
[1, 2, 3, 4, 5, 12]
>>> spam.append(6)
>>> spam
[1, 2, 3, 4, 5, 12, 6]
Unlike strings, lists are mutable and can be changed. The best way to change an item in a list is to do so by indexing.
>>> toast = [1, 2, 3]
>>> toast[0] = 100
>>> toast
[100, 2, 3]
>>> toast[1] = 200
>>> toast
[100, 200, 3]
>>> toast[2] = 300
>>> toast
[100, 200, 300]
There are a few ways to remove an item from a list, but because of Python culture dictates that there should be one preferable way to do something, I'll give an example that's fast and uses less code.
>>> juice = ["a", "b", "c"]
>>> del juice[1]
>>> juice
['a', 'c']
>>> del juice[0]
>>> juice
['c']
>>> del juice[0]
>>> juice
[]
>>> dog = ["bark", "talk", "beg"]
>>> del dog[:]
>>> dog
[]
You should notice that when you delete an item, the items move over to the left (if possible). So you could keep deleting item zero to remove all of the items. An easier way to delete a whole list is to follow the example with dog . This completely deletes all of the items in the list.
 |
Note: In the previous example, del dog[:] deletes the list, not the variable. If you wanted to delete the variable, but not the list, you would use del dog . This will be taught later in the course, so you don't have to worry too much about it. |
As stated earlier, lists are mutable types, which means their content can dynamically change. Take spam for example. Spam really isn't the list, it just points to the location of the list. Take an address book for another example. It contains the location of a house. It doesn't know what's in the house, it just knows where the house is. spam and the list have the same relationship as the address book and the house.
Now this leads to some important questions, primarily how would you copy spam if it contains the address of the list? Since spam contains the address, giving another variable the same address isn't going to help you.
>>> spam = [1, 2, 3]
>>> eggs = spam
>>> spam
[1, 2, 3]
>>> eggs
[1, 2, 3]
>>> spam[1] = 22
>>> spam
[1, 22, 3]
>>> eggs
[1, 22, 3]
As you can see from the above example, spam and eggs both point to the same list and that any change one of them makes, it affects the other. This is called a shallow copy. If you want two completely different lists, then you'll need to do a deep copy. When slicing, the return is always a deep copy, so we could preform a simple slice to create a new list for eggs .
>>> spam = [1, 2, 3]
>>> eggs = spam[:]
>>> spam
[1, 2, 3]
>>> eggs
[1, 2, 3]
>>> spam[1] = 22
>>> spam
[1, 22, 3]
>>> eggs
[1, 2, 3]
This is an important concept to remember early on so you don't run into any problems in the future.
.append()
Adds an item onto the end of the list.
>>> spam = [1, 2, 3]
>>> spam.append(4)
>>> spam
[1, 2, 3, 4]
.clear()
Removes all of the items in the list.
>>> eggs = [1, 2, 3]
>>> eggs.clear()
>>> eggs
[]
.count()
Returns the number of times a given item is found.
>>> votes = ["yes", "no", "yes", "yes", "no"]
>>> votes.count("yes")
3
>>> votes.count("no")
2
.extend()
Appends a list at the end of the list.
>>> bacon = [1, 2, 3]
>>> bacon.extend([4, 5, 6])
>>> bacon
[1, 2, 3, 4, 5, 6]
.index()
Finds the first index of a given item. The two optional parameters are for the start and end of the list's index, respectively.
>>> votes = ["yes", "no", "yes", "yes", "no"]
>>> vote.index("no")
1
>>> vote.index("yes")
0
>>> vote.index("yes", 1)
2
>>> vote.index("no", 2)
4
>>> vote.index("yes", 1, 4)
2
.insert()
Inserts an item at a certain index position. Remember that the indexing in Python starts at zero!
>>> jam = [1, 2, 3, 4]
>>> jam.insert(3, 3.5)
>>> jam
[1, 2, 3, 3.5, 4]
.pop()
Returns the content of the given index and then deletes it.
>>> toast = [1, 2, 3, 4]
>>> jelly = toast.pop(2)
>>> jelly
3
>>> toast
[1, 2, 4]
.remove()
Like .pop() , except that it doesn't return the item. This makes .remove() slightly faster than .pop() .
>>> pop = [1, 2, 3]
>>> pop.remove(2)
>>> pop
[1, 3]
.reverse()
This reverses the order of the list.
>>> coke = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> coke.reverse()
>>> coke
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
List Usage
Although lists are useful, they are about four to seven times slower than tuples, since lists aren't as static as they are. You also need to remember that large lists will usually have a higher penalty on performance, so try keep them short. As a general rule of thumb, use lists only when you need to dynamically hold information and values.
|