Python Lists

python
Python lists are ordered, mutable data structures used for storing related values known as items. The square brackets [ ] define a list literal and signify to Python that a particular set of operations and methods will be available to the items in the list. Since lists are mutable, we can make additions and deletions to them as necessary. Another feature is the ability to perform a single operation on all of the items in a list at once.

I like dogs so lets make a list of dogs to start exploring the power of lists.

In [77]:
dogs = ['Pudlepointer', 'Jack Russell', 'French Bulldog', 'Labradoodle']

Like other data types in Python, we can print a list. We should get output that looks just like the list we created.

In [78]:
print(dogs)
['Pudlepointer', 'Jack Russell', 'French Bulldog', 'Labradoodle']

Indexing Lists

 Since lists are a compound data container, or data type, we can access specific elements of the list using indexing methods. This makes it easy to select and edit or remove items from a list as well modify specific items. This indexed, oredered structure also makes it perform operarions on specific list items and to make new, smaller lists from specific items. This level of flexibiltiy is very useful in Python.

Lists in Python are ‘0’ based meaning the first item is in the ‘0’ location and the second item is in the ‘1’ location. To illustrate, I have used lists, list comprehension, and some functions from the IPython display library to make a table of our list of dogs and their indexed position. This list method is a little advanced and will be revisited later but it is a good example of one of the things you can do with lists.

In [79]:
 from IPython.display import HTML, display

 data = [['0', '1', '2', '3'],
         ['Pudlepointer', 'Jack Russell', 'French Bulldog', 'Labradoodle'],
         ]

 display(HTML(
    '
{}

.format(
        ''.join(
            {}

.format(''.join(str(_) for _ in row)) for row in data)
        )
 ))
0 1 2 3
Pudlepointer Jack Russell French Bulldog Labradoodle

As you can see in the index example above, in position ‘0’ is Pudle Pointer and in position ‘3’ is Labradoodle. I have four dogs, or items, in my list. I have four total items but my list my index only goes to 3. This is very important to remember when accessing list items.

To demonstrate indexing, lets print Pudle Ponter by calling its index from our list:

In [80]:
print(dogs[0])
Pudlepointer

To print French Bulldog we call position 2:

In [81]:
print(dogs[2])
French Bulldog

But what happens if we print position 4?

In [82]:
print(dogs[4])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
 in ()
----> 1 print(dogs[4])

IndexError: list index out of range

Oops; there is no poistion 4

It is also possible to access the list in reverse using negative numbers.

In [83]:
 data = [['-4', '-3', '-2', '-1'],
         ['Pudlepointer', 'Jack Russell', 'French Bulldog', 'Labradoodle'],
         ]

 display(HTML(
    '
{}

.format(
        ''.join(
            {}

.format(''.join(str(_) for _ in row)) for row in data)
        )
 ))
-4 -3 -2 -1
Pudlepointer Jack Russell French Bulldog Labradoodle

If we want to use the negative indexing to print a value from our list of dogs we do the following:

In [84]:
print(dogs[-3])
Jack Russell

We can also perform string concatination with items from a list.

In [85]:
print('My dog Millie is a ' + dogs[-4]+'.')
My dog Millie is a Pudlepointer.

Modifying List Items

It is also possible to change list items by using the index numbers. If we want to change ‘Labradoodle’ to ‘Griffon’ we can perform the following, using the index of [-1]:

In [86]:
dogs[-1] = 'Griffon'
print(dogs)
['Pudlepointer', 'Jack Russell', 'French Bulldog', 'Griffon']

List Sicing

It is possible to select a range of values from a list using the slicing method. A slice is created by separating a starting index and an ending index with a colon like so [x:y]. The first index value is inclusive whereas the last value, or stopping position, is exclusive. If we slice ‘dogs’ with [2:4] the result will be [‘French Bulldog’,’Griffon’].

In [87]:
print(dogs[2:4])
['French Bulldog', 'Griffon']

We can include either end of the list by omitting one of the numbers in the list[x:y] syntax. To print the first three items of dogs, positions 0,1,2, we would do the following:

In [88]:
print(dogs[:3])
['Pudlepointer', 'Jack Russell', 'French Bulldog']

If we want to print from the middle of the list to the end we would do so like this:

In [89]:
print(dogs[2:])
['French Bulldog', 'Griffon']

Negative indexing can also be used with slices:

In [90]:
print(dogs[:-2])
print(dogs[-1:])
print(dogs[-4:-2])
['Pudlepointer', 'Jack Russell']
['Griffon']
['Pudlepointer', 'Jack Russell']

Another trick with lists is slicing using stride. Stride will determine how many units we move up or down in a list; like counting by 2s or 5s. We have not been including the stride parameter in our slices so Python has been using the default of 1. The notation for slicing with a stride parameter is list[x:y:z]. This would produce a selection of items x:y by every zth item.

In [91]:
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','m','o','p','q','r','s','t','u','v',
           'w','x','y','z']

To see how long our list, ‘alphabet’, is we use the len() function.

In [92]:
len(alphabet)
Out[92]:
26

To select every third letter, beginning at the ‘0’ position, we can do any of the following:

In [93]:
print(alphabet)
print(alphabet[::3])
print(alphabet[0::3])
print(alphabet[:26:3])
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'm', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
['a', 'd', 'g', 'j', 'm', 'p', 's', 'v', 'y']
['a', 'd', 'g', 'j', 'm', 'p', 's', 'v', 'y']
['a', 'd', 'g', 'j', 'm', 'p', 's', 'v', 'y']

This feature provides a lot of control and flexibilty for us to use to access data in lists.

List Modification Using Operators

Mathematical operators, such as \*and + , can also be used to modify lists. Additionally, the common compound forms for these operators, \*= and += can be used.

It is common to use + to concatenate two lists and to add items to the end of a list.

In [94]:
print(dogs + alphabet)
['Pudlepointer', 'Jack Russell', 'French Bulldog', 'Griffon', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'm', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
In [95]:
dogs = dogs + ['Beagle']
print(dogs)
['Pudlepointer', 'Jack Russell', 'French Bulldog', 'Griffon', 'Beagle']

Using the \* operator it is possible to multiply a list by a factor and replicate the values.

In [96]:
print(dogs*2)
['Pudlepointer', 'Jack Russell', 'French Bulldog', 'Griffon', 'Beagle', 'Pudlepointer', 'Jack Russell', 'French Bulldog', 'Griffon', 'Beagle']

Using the compound operators \*= and \+= it is easy to automate the population of a list. We will use a for loop to add ‘Boder Collie’ to our list of dogs multiple times. We will add ‘Border Collie’ to our list of dogs four times, adding to each previous list.

In [97]:
for x in range(1,5):
    dogs += ['Border Collie']
    print(dogs)
['Pudlepointer', 'Jack Russell', 'French Bulldog', 'Griffon', 'Beagle', 'Border Collie']
['Pudlepointer', 'Jack Russell', 'French Bulldog', 'Griffon', 'Beagle', 'Border Collie', 'Border Collie']
['Pudlepointer', 'Jack Russell', 'French Bulldog', 'Griffon', 'Beagle', 'Border Collie', 'Border Collie', 'Border Collie']
['Pudlepointer', 'Jack Russell', 'French Bulldog', 'Griffon', 'Beagle', 'Border Collie', 'Border Collie', 'Border Collie', 'Border Collie']

\*= behaves in a similar way.

In [98]:
doggies = ['Bulldog']

for x in range(1,5):
    doggies *= 3
    print(doggies)
['Bulldog', 'Bulldog', 'Bulldog']
['Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog']
['Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog']
['Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog', 'Bulldog']

Removing Items from a List

There are a few ways to remove items from a list. The del statement can be used to delete based on index and the .pop() method can be used to select the last item from a list.

In [107]:
dogs = ['Pudlepointer', 'Jack Russell', 'French Bulldong','Griffon','Beagle','Labradoodle']


del dogs[2]
print(dogs)
['Pudlepointer', 'Jack Russell', 'Griffon', 'Beagle', 'Labradoodle']

Comparing the original list 'dogs' to the output list printed after the del you will see that 'French Bulldog' was deleted.

It is also possible to delete over a range of index positions. If we want to delete 'Jack Russell','Griffon','Beagle' we would type the following:

In [108]:
dogs = ['Pudlepointer', 'Jack Russell', 'Griffon','Beagle','Labradoodle']

del dogs[1:4]
print(dogs)
['Pudlepointer', 'Labradoodle']

.pop() will select the last item from a list like so:

In [110]:
dogs = ['Pudlepointer', 'Jack Russell', 'Griffon','Beagle','Labradoodle']
print(dogs.pop())
print(dogs)
Labradoodle
['Pudlepointer', 'Jack Russell', 'Griffon', 'Beagle']

Lists of Lists

It is possible to make a list that consists of other lists as its items. This is exactly what a comma delemited file (csv) is; a list of lists, or more appropriately, nested lists.

In [111]:
dog_park = [['Pudlepointer', 'Jack Russell', 'Griffon','Beagle','Labradoodle'],['Millie', 'Piper', 'Oakley', 'Jake','Mumford']]

Nested lists are accessed using indices similary to what was done previously. With the notation list[x][y] [x] is the list index in the nested list and [y] is the index of the item you want to select in the list.

In [113]:
print(dog_park[1][0])
print(dog_park[0][0])
Millie
Pudlepointer
In [120]:
print("The first nested list [0].")
print(dog_park[0][0])
print(dog_park[0][1])
print(dog_park[0][2])
print(dog_park[0][3])
print(dog_park[0][4])

print()

print("The second nested list [1].")
print(dog_park[1][0])
print(dog_park[1][1])
print(dog_park[1][2])
print(dog_park[1][3])
print(dog_park[1][4])
The first nested list [0].
Pudlepointer
Jack Russell
Griffon
Beagle
Labradoodle

The second nested list [1].
Millie
Piper
Oakley
Jake
Mumford

Final Thoughts

 List are very flexible and accessible data containers for holding ordered data. The examples above are just some of the basic things that can be done with lists. If you want to learn more, I recommend you read about list methods and list comprehensions to further your programming skills.

Thank you for reading this post. If you found it useful or you have some more information about Python lists, please share with me in the comments below or on Twitter.

Python image courtesy of www.python.org