How To Use Python Lists

How To Use Python Lists

A list is a collection of items in a particular order. They allow you to store various types of data as individual elements within the list. Python Lists are probably the most used type of construct to work with within the Python programming language. The concept of lists are fairly easy to grasp even for newer programmers, and they are an important foundation concept in Python as they are part of many different concepts in Python programming. In this tutorial, we’ll learn all about how to use Python lists.


What Is A Python List?

A list is a data structure in Python that is a mutable, ordered sequence of elements. Mutable just means that the list can be changed. Each element that is inside of a list is called an item. Lists are good for when you want to work with several related values. They make it easy to organize your data or to perform the same operation on multiple elements at the same time. You can make a list that includes the digits from 0–9, the letters of the alphabet, or the names of your favorite ice cream. Although grouping related items together in a list is common, you can put anything you want into a list, even if they are not related. Since a list usually has more than just one element, the variable name of a list is often plural.


How To Define A List In Python

Just as strings are defined as characters between quotes ' ', lists are defined by having values between square brackets [ ]. This code snipped defines an empty list in Python:

Here is an example list that has different vegetables. The individual elements in the list are separated by commas.

When you use the print() function in Python to display a list it returns a representation of the list, including the square brackets. The output looks just like the list we created:

['Kale', 'Cabbage', 'Celery', 'Asparagus', 'Lettuce']

Mixing Types In A List

This example list has an integer type, a string data type, a boolean value, a list, and a dictionary, all contained as elements of a list.

<class 'int'>
<class 'str'>
<class 'bool'>
<class 'list'>
<class 'dict'>

Python List Actions And Methods

Everything in Python is an object, and objects have methods. You can take various actions with these provided methods. The list object has several useful methods to use with lists. Let’s look at a few of them here.


.count()

The count() method returns the number of times the specified element appears in the list. This is the syntax for the count() method.

list.count(element)

The count() accepts just one argument when you call it, and that is the element to count occurrences of. Consider our list of vegetables:

You have 1 lettuce.

The .count() method confirms what we already knew, that there is just 1 ‘Lettuce’ in the list. If there were multiple ‘Lettuce’ in the list, the .count() method could count the number of times ‘Lettuce’ occurs and give us the value. That leads to our next Python list method, and that is .append().

list.append()

The append() method adds an item to the end of the list. The syntax for the append() method is as follows:

list.append(item)

append() takes a single argument of item, which is the item to be added to the end of the list. Since we can put any data type inside of a list, the appended item can be a string, number, list, dictionary, or any other data type. Let’s add another ‘Lettuce’ to our list so that we can test out the count() method again.

['Kale', 'Cabbage', 'Celery', 'Asparagus', 'Lettuce', 'Lettuce']

Cool! Now we can try that count() function again and see the result.

You have 2 lettuce.

list.index()

The index() list method returns the index of the specified element in the list. Its syntax is as follows:

list.index(element, start, end)

The list index() method has three possible arguments:

  • element – the element to be searched
  • start (optional) – start searching from this index
  • end (optional) – search the element up to this index

The index() method returns the index of the given element in the list and if the element is not found, you will get a ValueError Exception.

Asparagus is at index 3

The ‘Asparagus’ is at index 3. This is because lists begin at 0, not 1. Because the first index is 0, the last index is one less than the size of the list.

If the second parameter is provided, this is where index() begins its search from left to right. In the example here, we start searching at 4. Since ‘Asparagus’ is at index 3, the item is not found, and an exception is raised.

Traceback (most recent call last):
  File "C:/python/justhacking/lists.py", line 2, in <module>
    asparagus = veggies.index('Asparagus', 4)
ValueError: 'Asparagus' is not in list

In this next example, we will use three parameters for the index() method. We can specify the element to search for, the index to start searching at, and the index to end searching at. Since the item we look for is indeed in between the start and end index values, then we have a successful index lookup.

Celery is at index 2

To see the index of every item in a list in Python, you could use this neat little snippet of code which uses the enumerate() function to provide an index we can access in a for loop.

Kale us at index 0
Cabbage us at index 1
Celery us at index 2
Asparagus us at index 3
Lettuce us at index 4

If you know the index of a given item, it is then easy to access that item using the square bracket [ ] notation like so:

Cabbage
Kale
Asparagus
Celery
Lettuce

list.reverse()

If you want to reverse the order of the items in a list, you can call the reverse() list method. They sytax is as follows:

list.reverse()

No parameters are available with the .reverse() method and it reverses the list in place. This means it does not return a value, it modifies the actual list. This is why
you would use veggies.reverse(), instead of veggies = veggies.reverse().

['Lettuce', 'Asparagus', 'Celery', 'Cabbage', 'Kale']

We can use the index() method once again after having used the reverse() method. We can see that ‘Asparagus’ has changed the index position it is located at.

Asparagus is at index 1

The reverse() method changes the order of a list permanently, however you can go back to the original order by applying reverse() to the same list a second time if you need to.

Asparagus is at index 1
Now it is at index 3

list.clear()

The clear() method removes all items from the list and its syntax is as shown:

list.clear()

The clear() method doesn’t take any parameters and does not return a value. It simply empties a given list.

[]

list.copy()

The copy() method is used to create a shallow copy of the list and the syntax is displayed here:

copy_of_list = list.copy()

The copy() method doesn’t take any parameters and returns a new list. It does not alter the original list.

['Kale', 'Cabbage', 'Celery', 'Asparagus', 'Lettuce']
['Kale', 'Cabbage', 'Celery', 'Asparagus', 'Lettuce']

What’s interesting is that these look like the same list. They hold the same contents, but they are in fact two completely separate lists. We can prove that by running the id() function on each variable to see that they each have their own unique id.

58068200
58067816

A list can be copied using the = operator but the problem with copying lists this way is that if you the original *or* the new list, both lists are simultaneously affected with that change. This is because the copied list is only a reference. What you get in this scenario is basically two differently named variables, that both point to the same location in memory. Again, the id() function can show us that.

59313384
59313384

So if you want to make a new copy of a list, while making sure that each list is completely unique, use the .copy() method instead of the = operator.

list.extend()

If you have two lists that you want to add together, you can use the extend() list method in Python. It adds all the elements of an iterable to the end of the list. That means you can also add things besides lists like strings, tuples, or another iterable. The syntax is as follows:

list.extend(iterable)

Just like append(), remove(), sort(), and reverse(), the extend() method modifies the original list. It doesn’t return any value.

['Kale', 'Cabbage', 'Celery', 'Asparagus', 'Lettuce', 'Okra', 'Garlic']

This also works when the iterable you are adding is a tuple, set, string, or dictionary.

['Kale', 'Cabbage', 'Celery', 'Asparagus', 'Lettuce', 'Okra', 'Garlic']

['Kale', 'Cabbage', 'Celery', 'Asparagus', 'Lettuce', 'Okra', 'Garlic']

['Kale', 'Cabbage', 'Celery', 'Asparagus', 'Lettuce', 'B', 'r', 'o', 'c', 'c', 'o', 'l', 'i']

['Kale', 'Cabbage', 'Celery', 'Asparagus', 'Lettuce', 'Broccoli']

list.insert()

In addition to the append() method we learned about, there is also an .insert() method that can be used to add items to a list. The difference between append() vs insert() is that with append(), the value is added to the end of the list. When using the insert() method, a value can be inserted into the list wherever you like. The syntax of the insert() method is as follows:

list.insert(i, elem)

The insert() method simply returns None and updates the existing list. To insert an element at the beginning of the list, use index 0. To insert an element in the third position, use index 2.

['Spinach', 'Kale', 'Cabbage', 'Celery', 'Asparagus', 'Lettuce']

['Kale', 'Cabbage', 'Tomato', 'Celery', 'Asparagus', 'Lettuce']

['Kale', 'Cabbage', ('Turnip', 'Cucumber'), 'Celery', 'Asparagus', 'Lettuce']

list.pop()

The .pop() method is used to pop an item off of the end of the list. During this process, two things happen. The original list is modified, and the item being removed is returned so you can store that item in a variable. If you pass the pop method an index value, you are able to specify which item is popped out of the list. The syntax of the pop() method is:

list.pop(index)

  • The pop() method accepts just one argument (index).
  • If an argument is not passed, the default index -1 is passed as an argument (index of the last item).
  • If the index passed to the method is not in range, you will get an IndexError: pop index out of range exception.

Lettuce

Kale

Traceback (most recent call last):
  File "C:/python/justhacking/lists.py", line 2, in <module>
    least_favorite = veggies.pop(5)
IndexError: pop index out of range

list.remove()

If you won’t know the position of the value you want to remove from a list, but you still want to remove it, you can use the remove() method. It removes the first matching element (which is passed as an argument) from the list and its syntax is:

list.remove(element)

  • The remove() method accepts one element as an argument and removes it from the list.
  • If the element is not round, it throws ValueError: list.remove(x): x not in list exception.

['Cabbage', 'Celery', 'Asparagus', 'Lettuce']

['Kale', 'Cabbage', 'Asparagus', 'Lettuce']

list.sort()

Python’s sort() method makes it easy to sort a list. It sorts the elements of a given list in ascending or descending order with the syntax being:

list.sort(key=…, reverse=…)

  • reverse – If True, the list will be sorted in reverse (Descending) order
  • key – A function you define for sort comparison
  • The sort() method modifies the original list in place.
  • If you want to return the sorted list rather than change the original list, use sorted() instead.

['Asparagus', 'Cabbage', 'Celery', 'Kale', 'Lettuce']

['Lettuce', 'Kale', 'Celery', 'Cabbage', 'Asparagus']

['Asparagus', 'Cabbage', 'Lettuce', 'Celery', 'Kale']

What Is The list() Function?

Similar to how str(17) will return ’17’, the string representation of the integer 17, the list() function will return a list version of the value passed to it. One useful scenario for using the list() function is for converting a tuple to a list if you need a mutable version of a tuple value.

('Kale', 'Cabbage', 'Celery', 'Asparagus', 'Lettuce')
['Kale', 'Cabbage', 'Celery', 'Asparagus', 'Lettuce']

How To Use Random With Lists

Sometimes you want to get a random value out of a list, and Python provides a really easy way to do this with the random module.

Lettuce

How To Use Python Lists Summary

In this tutorial, we learned what lists are and how to work with the individual items in a list. We learned how to define a list and how to add and remove elements as well as sort lists. We had a look at built-in Python methods we can use with lists as well. Lists are a useful data type since they allow you to write code that works on a collection of values held in a single variable.