In this tutorial, you’ll learn all you need to know to get started with Python lists. You’ll learn what lists are and how they can be used to store data. You’ll also learn how to access data from within lists by slicing and indexing data. You’ll learn how to add data to lists and as well as how to delete items. You’ll also learn how to create lists of lists, which can often be used to represent matrices of data.
What are Python Lists
Python lists are a data collection type, meaning that we can use them as containers for other values. One of the great things about Python is the simplicity of naming items. Think of lists as exactly that: lists. Lists in real life can contain items of different types and can even contain duplicate items.
Let’s take a look at some of the key properties of Python lists:
|Python lists are…||Description|
|Ordered||Python lists are not just a collection of objects, but rather an ordered collection of objects. This means that the order that’s been defined matters. Unless the order is explicitly altered, the order remains the same.|
|Indexable||We can access Python list items using their index position. Because lists are ordered, the index remains the same (unless we explicitly alter it).|
|Mutable||We can change lists by applying different functions or methods on lists. This can include sorting values in different ways (such as smallest to largest) or filtering list values based on a condition.|
|Heterogeneous||Python lists can contain different types of objects. For example, you could create a list that contains information about different people, such as their name (string), age (integer), registration (boolean), and more!|
Now that you know what Python lists are, let’s take a look at how we can create them.
Creating Python Lists
Let’s now take a look at how we can create Python lists. To create an empty list, you have two different options:
- Using the
- Using empty square brackets,
Let’s take a look at what this looks like:
# Creating an Empty List in Python empty_list1 = list() empty_list2 = 
We can also create lists with data. To do this, let’s use square brackets and simply include data within it. Because lists are heterogenous, we can include different types of data.
Let’s now create a non-empty list:
# Creating a Non-Empty List list1 = ['Nik', 33, 'Toronto']
Here, we’ve created a list that contains three items. There may times when your lists are a little longer and you want to split them across multiple lines. Stylistically, you may want to indent them as shown below:
# Creating a Non-Empty List with Nicer Indentation list1 = [ 'Nik', 33, 'Toronto' ]
Both of these lists are exactly the same. If our list was wider or longer the second option would certainly be easier to read.
Checking the Type of a List
If you’re ever not sure of your object’s datatype, you can use the built-in type() function to check the objects type. Let’s pass one of our lists into the function and see what it returns:
# Checking the type of a list list1 = list() print(type(list1))
The returns the following:
In the next section, you’ll learn how to access data in Python lists.
Accessing Data in Python Lists
We can access Python list items using a number of different ways. Remember, Python lists are indexed and ordered. This means that we can access items based on the order in which they appear (i.e., their index position).
Python list indexes are
0-based, meaning that they start at the value of 0 and end at the value of the length of the list minus 1. Inversely, list indexing can also from the end. The last item has an index position of -1 and continues through to the negative value of the length of the list.
Let’s load a list so that we can see how the list indices represent different values:
# Loading a Sample List letters = ['a', 'b', 'c', 'd', 'e', 'f']
While it may seem counterintuitive that negative indices should start at -1, it may help to think of indices as being the boundary between different list items.
Using a List Index to Access an Item
Let’s see how we can use an index, both a positive index and a negative index, to access a list’s items. Remember, the first item will have an index position of 0 and the last item will have a negative index of -1.
Let’s see how we can use our list to access both the first and last items in our lists:
# Accessing List Items with Indexing letters = ['a', 'b', 'c', 'd', 'e', 'f'] first_item = letters last_item = letters[-1]
Because lists are mutable (meaning they can be changed), using negative indices can be particularly helpful. Since the length of our list may change, you don’t first need to know how long your list is to access the last item.
Now, what do you think will happen when we try to write the code below?
letters = ['a', 'b', 'c', 'd', 'e', 'f'] print(letters)
There may also be times when you want to select more than one item in your list. Say you want to select a subsection of your list – this is what you’ll learn in the next section.
Slicing Python Lists to Access Multiply Items
Python lists are also sliceable, meaning that we can easily access a subsection of a list. We include a starting and an ending index position inside of our square brackets, separated by a colon.
Let’s see how we can access the second through fourth items in our list:
# Slicing a Python List - As Easy as Slicing Pie! letters = ['a', 'b', 'c', 'd', 'e', 'f'] slice = letters[1:4] print(slice) # Returns: ['b', 'c', 'd']
There’s a couple of things to make note of here:
- The returned slice is also a list
- The ending parameter is non-inclusive, meaning that it includes all items up to, but not including, that index item
We can also omit either the starting or ending (or both) positions of a slice. This returns all values on either end (or both ends). This is particularly helpful when we don’t know how a long a list is but want to include everything to the end. Similarly, we can combine negative indexing with our slicing.
Check your understanding: Go through the exercises below to test your knowledge on what items would be included in the slice. Remember that our list looks like this:
letters = ['a', 'b', 'c', 'd', 'e', 'f'].
Now that you have a strong understanding of how list items can be accessed, let’s take a look at how we can modify list items.
Modifying Python List Items
Knowing how to access list items allows us to easily modify them. We can simply assign a new value to a list item’s index and the item in that position will be modified. Because Python lists are heterogeneous (meaning that they can contain different data types), we don’t need to worry about the data type that we’re assigning in.
Let’s see how we can modify the first item of our earlier list:
# Modifiying the first item in a Python list letters = ['a', 'b', 'c', 'd', 'e', 'f'] letters = 'g' print(letters) # Returns: ['g', 'b', 'c', 'd', 'e', 'f']
We can see how easy it was to change a list’s item.
Similarly, we can also modify a slice of a list by passing in another list of items:
# Modifying Multiple Items in a List letters = ['a', 'b', 'c', 'd', 'e', 'f'] letters[0:2] = ['g', 'h'] print(letters) # Returns: ['g', 'h', 'c', 'd', 'e', 'f']
Now, what do you think will happen when we try to write the code below?
letters = ['a', 'b', 'c', 'd', 'e', 'f'] letters = 'g'
Open the tab below to see what the result of this would be:
In the next section, you’ll learn how to check if an item exists in a list.
Check if an Item Exists in a Python List
There are many times when you simply want to know whether an item exists in a list or not. In order to do this, we can make use of the
in keyword. Quite literally, the keyword will evaluate whether or not an item exists in a list or not. This is one of the huge benefits of Python – its emphasis on readability.
The use of the keyword will return a boolean condition:
- If an item exists, the expression will evaluate to
- If an item doesn’t exist, the expression will evaluate to
Let’s see if the string
'a' exists in our list:
# Checking if an item exists in a list letters = ['a', 'b', 'c', 'd', 'e', 'f'] print('a' in letters) # Returns: True
Here, we can see that our code evaluated to
True, since the string does exist in our list. Similarly, we can confirm that the string
'datagy' doesn’t exist in our list:
# Checking if an item doesn't exist in a Python list letters = ['a', 'b', 'c', 'd', 'e', 'f'] print('datagy' in letters) # Returns: False
In the following section, you’ll learn some of the ways with which you can add items to a Python list.
Add Items to Python Lists
Because Python lists are inherently collection data types, we’ll often want to use them to store data. One of the most common operations will be to be add items to Python lists. While in the previous section, you learned how to modify items in a list, this section will walk you through adding items to a list.
Python comes with a list method,
.append(), which allows you to, well, append items to a list.
Let’s see how we can add the string
'g' to our previous list:
# Appending Items to a Python list letters = ['a', 'b', 'c', 'd', 'e', 'f'] letters.append('g') print(letters) # Returns: ['a', 'b', 'c', 'd', 'e', 'f', 'g']
One important thing to note here is that the
.append() method works in-place. This means that, since our list is mutable, we don’t need to re-assign it to a new variable in order to use it.
We can even add multiple items to a list! Let’s see what happens when we use the
.append() method to add a list of items to another list:
# Appending Multiple Items to a Python list letters = ['a', 'b', 'c', 'd', 'e', 'f'] letters.append(['g', 'h']) print(letters) # Returns: ['a', 'b', 'c', 'd', 'e', 'f', ['g', 'h']]
We can see that that’s not exactly what we wanted! The entire list was inserted, as a list, into our list. You’ll learn more about lists of lists later in this lesson. The
.append() method takes only a single argument and the entire argument is added.
In order to append multiple items at the same time to a Python list, we want to use the
.extend() method. This method adds all of the elements of an iterable object (like a list) to the end of a list. Let’s repeat our earlier example with this new method!
# Appending Multiple Items to a Python list with .extend() letters = ['a', 'b', 'c', 'd', 'e', 'f'] letters.extend(['g', 'h']) print(letters) # Returns: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
This worked much better and gave us the result we had been hoping for!
Remove Items from Python Lists
Now that you know how to add items to a list, let’s see how we can use Python to remove items from a list. There may be a number of different ways in which you may want to remove items from a list.
For example, you may want to remove simply the second item of a list (i.e., by position) or remove a particular item (i.e., by value). While there are a number of additional ways in which you can remove items from a list, lets start with these first.
Remove Items from a List by Index Position
Knowing how to remove an item from a list by using its index position is an important skill. For example, you may simply know you want to remove the second item from a list. For this, you can make use of the
.pop() method takes a single argument, the index of the item you want to remove. Furthermore, it actually returns the item, which can be quite handy if you want to make use of the item you just removed. This can be particularly helpful in building games.
Let’s take a look at how to use this method to remove the second item in our list:
# Removing the second item from a list using .pop() letters = ['a', 'b', 'c', 'd', 'e', 'f'] dropped_letter = letters.pop(1) print('Dropped letter: '+dropped_letter) print('letters = ', letters) # Returns: # Dropped letter: b # letters = ['a', 'c', 'd', 'e', 'f']
We can see here that by using the
.pop() method that we were able to remove an item from a list using its position.
Remove an Item from a Python List by Its Value
Similarly, we can remove an item from a Python list using its value. For this, we can use the aptly-named
.remove() method. Similar to the
.pop() method, this method takes only a single argument: the value that we’re hoping to remove. Unlike the
.pop() method, this method doesn’t return anything.
Let’s see how we can use Python to remove the string
'c' from our list:
# Removing an item from a list using .remove() letters = ['a', 'b', 'c', 'd', 'e', 'f'] letters.remove('c') print(letters) # Returns: ['a', 'b', 'd', 'e', 'f']
Here, we can see that our list was successfully altered to have removed the string
'c'. Take a look at the code below and try and guess what will happen:
letters = ['a', 'b', 'c', 'd', 'e', 'f'] letters.remove('g')
One important thing to note is that the method removes only the first instance of that item in our list. One way that we can work around this to simply call the method multiple times. However, as you saw in the above example, our code will fail if an item doesn’t exist – so tread carefully!
Iterating over Python Lists
There may also be many times when you want to iterate (or loop) over items in a list. Python actually makes this very easy to write (and to read). We can simply ask Python to do something “for” each item “in” our list. Say we wanted to print out every string in our list
letters, we could simply write the following:
# Iterating over a Python list letters = ['a', 'b', 'c', 'd', 'e', 'f'] for letter in letters: print(letter) # Returns: # a # b # c # d # e # f
That was easy! One of the great things about Python is how similar to English it really is. It’s immediately clear what we’re hoping to do.
Something to make note of here is that our choice of using the iterator
letter is completely optional. We can actually name it whatever we want. For example, writing the code below would yield the exact same result:
# Iterating over a Python list letters = ['a', 'b', 'c', 'd', 'e', 'f'] for gobbledygook in letters: print(gobbledygook) # Returns: # a # b # c # d # e # f
Something that may seem minor when you’re writing your code is the choice for variable names. It’s important to strive for readability in your code. Because of this, the choice of
letter probably makes more sense than
You’ll learn more about Python for loops in an upcoming lesson, but I wanted to include a quick overview of them in regards to lists here for completeness. In the next section, you’ll learn about Python list comprehensions.
Python List Comprehensions
Python list comprehensions are a bit more an advanced topic. In short, Python list comprehensions are short, concise ways of creating lists. Don’t worry if this material is a bit out of reach at the moment. I cover list comprehensions extensively in other tutorials – for now, it’s more important to know that they exist!
The image below shows the syntax of how a Python list comprehension works.
We create a new list and then evaluate an expression for each item in another iterable item.
For example, if we had a list that contained the values from 1 through 10, we could use a list comprehension to create a new list of all the squared values of these numbers.
Let’s see how we can do this with a list comprehension:
# A Simple List Comprehension Example numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] squares = [number ** 2 for number in numbers] print(squares) # Returns: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
We can see that this is a fairly readable approach to creating new lists. It can often be easier for beginners to read these and make sense of them than to write them. Because of this, if these don’t immediately make sense, don’t despair!
In the following section, you’ll learn more about Python lists of lists.
Python Lists of Lists
Because Python lists are simply container objects, they can actually contain other lists. This may sound a little odd at first, but the more you work with the language the more sense this will actually make.
You can actually think list of lists as being similar to matrices to hold data. Because lists themselves are ordered, this can be a logical way of storing data. For example, you can use each nested list to store information about different customers and use the outer list to store all the other lists. This saves you the effort of initializing new variables for each list.
Let’s see what this might look like:
# A Simple List of Lists customers = [ ['Nik', 32, 'Toronto'], ['Kate', 33, 'Paris'], ['Nate', 27, 'Nashville'], ]
Now, each item in our list
customers is actually a list. Because of this, if we were to access the first item using the index of 0, we would actually simply return the first list.
# Accessing items in a list of lists customers = [ ['Nik', 32, 'Toronto'], ['Kate', 33, 'Paris'], ['Nate', 27, 'Nashville'], ] print(customers) # Returns: ['Nik', 32, 'Toronto']
If we wanted to access the first item in our first list, we could simply chain our index accessors.
# Accessing the first item in our first sublist customers = [ ['Nik', 32, 'Toronto'], ['Kate', 33, 'Paris'], ['Nate', 27, 'Nashville'], ] print(customers) # Returns: Nik
Lists of lists are one way to store data. They aren’t however, the best way to store large amounts of tabular data. For this, you may want to look toward using Numpy and Pandas, which you’ll learn about in future tutorials.
Conclusion and Recap
Phew! This was a long tutorial! You learned about the Python list data structure and its different attributes. You then learned how to work with lists, such as checking for membership, adding and removing items, and accessing data within lists.
Below, you’ll find a quick recap of Python lists:
- Python lists are heterogenous, mutable, ordered data structures
- They can be created using the
list()function or square-brackets
- Because they’re ordered and indexed, you can access individual items using the
[index]indexing method, or multiply items using slicing
- You can add items using the
.extend()methods and you can remove items using the
- You can loop over lists using simple for loops and you can use list comprehensions to easily create lists in a concise manner
- Finally, you can use lists of lists to store more complex data structures, such as those meant to be represented in a tabular way
Next, you’ll learn about how to use Python conditions and conditional expressions to further modify your Python programs!
Check out these related tutorials to learn about related topics: