Lists

Lists in Python are one of the most versatile collection object types available. The other two types are dictionaries and tuples, but they are really more like variations of lists.

Python lists do the work of most of the collection data structures found in other languages and since they are built-in, you don't have to worry about manually creating them. Lists can be used for any type of object, from numbers and strings to more lists. They are accessed just like strings (like slicing and concatenation) so they are simple to use and they're variable length, i.e. they grow and shrink automatically as they're used. In reality, Python lists are C arrays inside the Python interpreter and act just like an array of pointers.

Just so you know what exactly I’m talking about, here is a couple of quick examples that creates a list and then does a couple of manipulations to it.


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

>>>print list

[1, 2, 3, 4, 5]

>>>print list[0] #print the list item at index 0

1

>>>list.pop() #remove and print the last item

5

>>>print list #show that the last item was removed

[1, 2, 3, 4]

Here's a list of common list operations:

The biggest thing to remember is that lists are a series of objects written inside square brackets, separated by commas. Dictionaries and tuples will look the same except they have different types of brackets.

List usage

Lists are most often used to store homogenous values, i.e. a list usually holds names, numbers, or other sequences that are all one data type. They don’t have to; they can be used with whatever data types you want to mix and match. It’s just usually easier to think of a list as holding a “standard” sequence of items.

The most common use of a list is to iterate over the list and perform the same action to each object within the list, hence the use of similar data types. Time for an example:


>>> mylist = ["one", "two", "three"]

>>> for x in mylist:

... print "number " + x

...

number one

number two

number three

In the above example, the list was created. Next, a simply for loop was used to iterate through the list, prepending the word “number” to each list object and printing them out. We will talk about for loops later but this is a common use of them.

One thing to note right now, however, is that you can use whatever value for “x” that you want. You can use whatever name you want instead of “x”. I mention this because it kind of threw me for a loop when I first encountered it in Python. In other languages, loops like this are either hard-wired into the language and you have to use its format or you have to expressly create the “x” value before hand so you can call it in the loop. Python’s way is much easier because you can use whatever name makes the most sense, or you can simply use a “generic variable” like I did.

I won't go into the simple actions for lists since they work just like string operations. You can index, slice, and manipulate the list like you can for strings. In reality, a string is more like a modified list that only handles alphanumeric characters.

If you have questions, look at the String Tutorial; if you still have questions, look at the official Python documentation. Just remember that the resulting object will be a new list (surrounded by square brackets) and not a string, integers, etc.

Adding List Elements

Adding new items to a list is extremely easy. You simply tell the list to add it.


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

>>>newlist.append(54)

>>>newlist

[1, 2, 3, 54]

>>>a_list = [“eat”, “ham”, “Spam”, “eggs”, “and”]

>>> a_list.sort() # sort list items ('S' > 'e')

>>> a_list

['Spam', 'and', 'eat', 'eggs', 'ham']

The append method simply adds a single item to the end of a list; it's different from concatenation by expecting a single object and not a list. It also changes the list in-place and doesn't create a brand new list object.

Here's a note about append and sort from the book "Learning Python" from O'Reilly.

Here's another thing that seems to trip up new users: append and sort change the associated list object in-place, but don't return the list as a result (technically, they both return a value called None, which we'll meet in a moment). If you say something like L = L.append(X), you won't get the modified value of L (in fact, you'll lose the reference to the list altogether); when you use attributes such as append and sort, objects are changed as a side effect, so there's no reason to reassign.

If you want to put the new item in a specific position in the list, you have to tell the list which position it should be in. You have to use the index of what the position is.


>>>newlist.insert(1, 69)

>>>newlist

[1, 69, 2, 3, 54]

Remember, the index starts at 0, not 1. Hence, the example above inserted the number “69” into the second position, which is index 1.

You can add a second list to an existing one by using the extend method. Essentially, the two lists are concatenated (linked) together, like so:


>>>newerlist = [“Mary”, “had, “a”, “little”, “spam.”]

>>>newlist.extend(newerlist) #extending with named list

>>> newlist

[1, 69, 2, 3, 54, 'Mary', 'had', 'a', 'little', 'spam.']

>>>newerlist.extend([“It’s”, “grease”, “was”, “white”, “as”, “snow.”]) #extending inline

>>> newerlist

['Mary', 'had', 'a', 'little', 'spam.', "It's", 'grease', 'was', 'white', 'as', 'snow.']

Be aware, there is a distinct difference between extend and append. extend takes a single argument, which is always a list, and adds each of the elements of that list to the original list; the two lists are merged into one. append takes one argument, which can be any data type, and simply adds it to the end of the list; you end up with a list that has one element which is the appended object. Here’s an example from "Dive into Python":


>>> li = ['a', 'b', 'c']

>>> li.extend(['d', 'e', 'f'])

>>> li

['a', 'b', 'c', 'd', 'e', 'f'] #merged list

>>> len(li) #list length

6

>>> li[−1] #reverse index

'f'

>>> li = ['a', 'b', 'c']

>>> li.append(['d', 'e', 'f'])

>>> li

['a', 'b', 'c', ['d', 'e', 'f']] #new list object as an element

>>> len(li)

4

>>> li[−1] #the single list object

['d', 'e', 'f']

Mutability

One of the special things about lists is that they are mutable, i.e. they can be modified in place without creating a new object. The big concern with this is remembering that, if you do this, it can affect other references to it. However, this isn't usually a large problem so it's more like something to keep in mind if you get program errors.

Here's an example of changing a list using offset and slicing:


Generic Code Example:

>>> L = ['spam', 'Spam', 'SPAM!']

>>> L[1] = 'eggs' # index assignment

>>> L

['spam', 'eggs', 'SPAM!']

>>> L[0:2] = ['eat', 'more'] # slice assignment: delete+insert

>>> L # replaces items 0, 1

['eat', 'more', 'SPAM!']


Because lists are mutable, you can also use the del statement to delete an item or section. Here's an example:


Generic Code Example:

>>> L

['SPAM!', 'eat', 'more', 'please']

>>> del L[0] # delete one item

>>> L

['eat', 'more', 'please']

>>> del L[1:] # delete an entire section

>>> L # same as L[1:] = []

['eat']

Methods

I'll talk about methods more in the object-oriented programming chapter, but for the curious, a method works like a function in that you have the method name followed by arguments in parentheses. The big difference is that a method is qualified to a specific object with the period sign. In some of the examples above, the list object was affected by a method by using the “.” (dot) nomenclature. The “.” told the Python interpreter to look for the method name that followed the dot and perform the actions in the method on the associated list object.

Because everything in Python is an object, nearly everything has some sort of a method. You probably won’t be able to remember all the methods for every single object type, but remembering the most common and useful ones will speed up development. Having a list of the methods for each object type is very handy. You’ll find lists of the most common methods for each object type in the appendices of this book.

Finally, you need to remember that only mutable objects can be changed in-place; strings, tuples, and other objects will always have to create new objects if you change them. You also need to remember that modifying an object in place can affect other objects that refer to it.