Python Lists - Python (2016)

Python (2016)

CHAPTER 9: Python Lists

In Python, a list is an important data type which allows the user to keep sets of iterable items. A list is a mutable sequence—meaning that you can have a long list of items. You can denote a list using square brackets ([]). For the list to hold actual items, you have to place them within the brackets separated by commas.

Here are a few examples of a list:

>>>[78,92,56,1491]

[78,92,56,1491]

>>>[“h”,”i”,”t”,”h”,”e”,”r”,”e”,”!”]

[‘h’,i’,’t’,’h’,’e’,’r’,’e’,’!’]

You can also convert a non-list into a list, using the built-in Python function “list()”. This will be further discussed later on, but this is how it looks like:

>>>list[“Python”]

[‘P’,’y’,’t’,’h’,’o’,’n’]

A list is also capable of holding different data types, so a programmer can safely mix strings, numbers, and even complexes. You can also nest lists within lists:

>>>[[5,4,7,6],[“a”,”x”,”o”].[True, True, False]]

[[5,4,7,6],[‘a’,’x’,’o’].[True, True, False]]

Obviously, nesting can get pretty complicated as the nests go deeper and deeper. However, it can be leveraged into a powerful tool that will be harnessed at a later segment in this course.

List Indexing

Just like how strings can be indexed, so can lists. Indexing can then be used to get a specific item from the list. For example, if you wish to have the letter “o” extracted from [‘P’,’y’,’t’,’h’,’o’,’n’], you will have to types [‘P’,’y’,’t’,’h’,’o’,’n’][4]. For brevity, though, the list can be placed within a variable first. And again, do not forget that indexing always starts at zero, even in indexes.

Just like strings, one can index starting from the last item using negative numbers. Note as well that a -0 does not exist, and is just interpreted as 0. You should instead use -1 if you want to start counting from the end. And of course, if you try to index with a number that is out of range, then an index error will return.

List Slicing

And like strings, lists can also be sliced. When slicing a list, it will return with a newly sliced copy of the main list—meaning, the answer will also be a list.

List Manipulation

Manipulating lists is also quite basic. The best way to add a new item to a list is to use the built-in Python function “append()”. This can be done easily, as shown below:

>>>spam=[5,4,3,2,1]

>>>spam.append(7)

>>>spam

[5,4,3,2,1,7]

Unlike strings, however, lists can be changed—they are mutable. The best way that this can be done is through indexing. Below is a demonstration:

>>>spam=[1,2,3]

>>>spam[0]=50

>>>spam

[50,2,3]

As you see, we were able to change the first value in the list.

As far as removing items from lists go, there are a few ways for this to be achieved. However, because the 13th Zen so dictates, there should be a path of least resistance that should be most preferable. This is demonstrated below:

>>>toast=[1,2,3]

>>>del toast[1]

>>>toast

[1,3]

As you noticed, the simplest way is simply to append the “del()” function to the index number of the item that you wish to delete. Note as well that when an item is deleted, the remaining items move to the left (when applicable). If you keep on deleting the item “0”, then the entire list will be deleted soon enough. Instead of this, however, the most efficient way to delete an entire list is as follows:

>>>toast=[1,2,3]

>>>del toast[:]

This kind of function totally removes all the items from the list. Note that this example only deletes the list, however—the variable is still there. If you wanted to delete the variable itself, you should use “del dog”. This will be further explained in a later chapter.

As previously mentioned, the list is a mutable type—this means that content may change dynamically. Take, for example, the hypothetical list “spam”. This is not the list, but a variable that points to the location of the list. Another real-world example is an address book—it points to the location of the house, but not the house itself. Also, it does not know what is in the house. The list “spam” has the same traits.

This leads us to some questions—foremost is, how would one copy the list “spam” if it only has the address of the list? Since the variable contains the address, giving a different variable this same address will not help. Consider the following:

>>>spam=[1,2,3]

>>>toast=spam

>>>spam

[1,2,3]

>>>toast

[1,2,3]

>>>spam[1]=5

>>>spam

[1,5,3]

>>>toast

[1,5,3]

As we saw from this example, the variables “spam” and “toast” both point to exactly the same list—any change that will point to any of these variables will change the other one as well. This is like having two separate addresses point to the same house. In Python, this is called “shallow copy”. For those who want to have two completely different lists (think of two identical but physically different houses, on separate addresses), you will need to do what is called a “deep copy”. The language always creates a deep copy for slice operations, so a simple slice can create a new list for “toast”:

>>>spam=[1,2,3]

>>>toast=spam[:]

>>>spam

[1,2,3]

>>>toast

[1,2,3]

>>>spam[1]=5

>>>spam

[1,5,3]

>>>toast

[1,2,3]

Remember this, because it is a very important concept. It can save you lots of headaches in the more advance sections.

Built-in Functions

This section will tackle the different list functions built into Python.

.append() - This adds an item to the end of the list.

>>>spam=[1,2,3]

>>>spam.append(5)

>>>spam

[1,2,3,5]

.clear() - This removes all of the items from the list

.count() - This returns the number of times that a given item appears in the list.

>>>spam=[1,2,3,5,5,1,5,4]

>>>spam.count(5)

3

>>>spam.count[1]

2

.index() - This will find the index of any given item within the list. There are two optional parameters for the start and end of the index.

>>>spam=[1,2,3,5,5,1,5,4]

>>>spam.index(5)

3

>>>spam.index(1)

0

>>>spam.index(5,1)

4

>>>spam.index(1,2)

5

.extend() - This appends a list at the end of the list.

>>>eggs=[1,2,3]

>>>eggs.extend=[1,2,9]

>>>eggs

[1,2,3,1,2,9]

.insert() - This inserts an item into a certain index position. Again, remember that Python’s indexing begins at zero.

>>>bacon=[1,2,3,4,5]

>>>bacon.insert(2,”jam”)

>>>bacon

[1,2,’jam’,3,4,5]

.pop() - This will return the content of a specific index, after which it is deleted.

>>>spam=[1,2,3,4,5]

>>>eggs=spam.pop(2)

>>>eggs

3

>>>spam

[1,2,4,5]

.remove() - Just like .pop(), except that it does not return the item before deleting it. This makes this function slightly faster than .pop().

>>>jam=[1,2,3,4,5]

>>>jam.remove(2)

>>>jam

[1,2,4,5]

.reverse() - This will reverse the list’s order.

>>>juice=[1,2,3]

>>>juice.reverse()

>>>juice

[3,2,1]

Lists are very useful assets, and they offer a lot of flexibility. However, remember that there are other alternatives—such as tuples, which are four to seven times faster and are a lot more static than lists). Because of lists’ inherent characteristics, very long lists can usually incur a penalty in the program’s performance. This is why most lists are best kept short. In Python’s rule of thumb, lists are best used by those who wish to dynamically hold values and information.