I like dogs so lets make a list of dogs to start exploring the power of lists.
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.
print(dogs)
Indexing Lists
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.
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)
)
))
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:
print(dogs[0])
To print French Bulldog we call position 2:
print(dogs[2])
But what happens if we print position 4?
print(dogs[4])
Oops; there is no poistion 4
It is also possible to access the list in reverse using negative numbers.
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)
)
))
If we want to use the negative indexing to print a value from our list of dogs we do the following:
print(dogs[-3])
We can also perform string concatination with items from a list.
print('My dog Millie is a ' + dogs[-4]+'.')
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]:
dogs[-1] = 'Griffon'
print(dogs)
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’].
print(dogs[2:4])
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:
print(dogs[:3])
If we want to print from the middle of the list to the end we would do so like this:
print(dogs[2:])
Negative indexing can also be used with slices:
print(dogs[:-2])
print(dogs[-1:])
print(dogs[-4:-2])
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.
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.
len(alphabet)
To select every third letter, beginning at the ‘0’ position, we can do any of the following:
print(alphabet)
print(alphabet[::3])
print(alphabet[0::3])
print(alphabet[:26:3])
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.
print(dogs + alphabet)
dogs = dogs + ['Beagle']
print(dogs)
Using the \*
operator it is possible to multiply a list by a factor and replicate the values.
print(dogs*2)
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.
for x in range(1,5):
dogs += ['Border Collie']
print(dogs)
\*=
behaves in a similar way.
doggies = ['Bulldog']
for x in range(1,5):
doggies *= 3
print(doggies)
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.
dogs = ['Pudlepointer', 'Jack Russell', 'French Bulldong','Griffon','Beagle','Labradoodle']
del dogs[2]
print(dogs)
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:
dogs = ['Pudlepointer', 'Jack Russell', 'Griffon','Beagle','Labradoodle']
del dogs[1:4]
print(dogs)
.pop()
will select the last item from a list like so:
dogs = ['Pudlepointer', 'Jack Russell', 'Griffon','Beagle','Labradoodle']
print(dogs.pop())
print(dogs)
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.
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.
print(dog_park[1][0])
print(dog_park[0][0])
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])
Final Thoughts
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.