A Guide to Python Lists

by John | June 17, 2023

 

 

Why Lists Are Important

 

Python lists are an important concept to learn because they allow you to store and organize multiple pieces of information in one place. Imagine you have a bunch of items, like books or fruits, and you want to keep them together in a neat way. A list in Python lets you do just that!

Lists are like containers that can hold different types of data, such as numbers, words, or even other lists. They are flexible and can be changed, meaning you can add, remove, or modify items inside them whenever you need to.

By learning about Python lists, you gain the ability to work with collections of data more effectively. You can perform various operations on lists, like accessing specific elements, sorting them, or looping through each item to perform certain actions. This makes lists useful in solving many programming problems and building more complex programs.

In addition, lists are widely used in Python and form the foundation of other important data structures, such as queues, stacks, and linked lists. So, understanding lists is not only valuable on its own but also sets the stage for learning more advanced concepts in programming.

Overall, Python lists are essential because they provide a flexible and convenient way to store and manipulate multiple items, allowing you to write more powerful and efficient code.

 

 

Lets take some examples of lists as shown in the code snippet below. Notice that to create a list in python we should use the [] brackets so python knows that we want to create a list. Using a difference type of brackets will assign the data to a different type of structure. 

 

nums = [1, 2, 3, 4, 5]

letters = ['a', 'b', 'c', 'd', 'e']

animals = ['cat', 'dog', 'elephant', 'tiger', 'rabbit']

places = ['London', 'Paris', 'New York', 'Rome', 'Madrid']

 

So as we see above we have created 4 lists , inside each list we have added 5 elements , an element is the commonly used definition to describe an individual value within a list. There is no limit to the number of elements that can be contained within a list. 

 

 

Length of a List

 

The length of a list refers to the number of elements it contains. In other words, it tells you how many items are stored within the list. The length of a list can be obtained using the len() function in Python.

 

places = ['London', 'Paris', 'New York', 'Rome', 'Madrid']
length_places_list = len(places)
print(f'length of places list is {length_places_list}')

'''
length of places list is 5
'''

 

Any time an element is added to a list the length will increase by 1. 

 

places = ['London', 'Paris', 'New York', 'Rome', 'Madrid', 'Tokyo']
length_places_list = len(places)
print(f'length of new places list is {length_places_list}')

'''
length of new places list is 6
'''

 

 

List Indexing 

 

In the context of a list in Python, the index refers to the position of an item within the list. Every item in a list is assigned an index starting from 0 for the first item, 1 for the second item, and so on. The index allows you to access and retrieve specific elements from the list.

As mentioned, the index of a list starts at 0, so retrieving the 1st item within a list requires 

 

 

Index Animals
0 cat
1 dog
2 elephant
3 tiger
4 rabbit

 

 

To retrieve an element of a list we should use squares brackets along with the index we want to retrieve. So for example:


 


idx1 = animals[0]
idx2 = animals[1]

print(idx1, idx2)

'''
cat dog
'''

 

 

Now we can try an interactive exercise, take the list below and experiment with retrieving the elements from a given index. Note that with indexing you can also input a negative index. So for example 

 

animals = ['cat', 'dog', 'elephant', 'tiger', 'rabbit']

print(animals[-1], animals[-2])
'''
rabbit tiger
'''

 

Think of using a negative index as moving from right to left, whereas positive indices are moving left to right. 

 

Below you can try the interactive exercise below by typing the index and seeing if the output is what you expect. 

 


 

animals = ['cat', 'dog', 'elephant', 'tiger', 'rabbit']

 

 

 


 

 

Note that if you insert an index that is larger the length of the list minus -1 you will get an index error that looks like the print below

 

IndexError: list index out of range

 

However, when using negative indices, if you type in a value which has an absolute value less than the length of the list you will receive the same error. 

 

To verify this is true you can try typing -5 which will return 'cat' and 4 which will return 'rabbit' , then if you try -6 or less or 5 or greater you will receive the index error. 

 

We invite the reader to attempt inputting say 1.22 or some number with a floating decimal. Note you will receive an error that looks like 

 

TypeError: list indices must be integers or slices

 

This means you have attempted to use something other than an integer e.g. 

 

animals[1.22]

 

 

 

 

Appending to a List

 

Appending to a list means adding a new element to the end of an existing list. In Python, lists are mutable, which means they can be modified after they are created. The append() method is used to add an item to the end of a list.

When you append an element to a list, it increases the size of the list by one, and the new element becomes the last item in the list. The original elements in the list remain in their original positions, and the new element is placed at the end.

Appending is a common operation when you want to dynamically grow a list by adding new elements as needed. It allows you to expand the list without explicitly specifying its size or redefining it.

 

animals = ['cat', 'dog', 'elephant', 'tiger', 'rabbit']


animals.append('donkey')

print(animals)
'''
['cat', 'dog', 'elephant', 'tiger', 'rabbit', 'donkey']
'''


animals.append('fish')


print(animals)
'''
['cat', 'dog', 'elephant', 'tiger', 'rabbit', 'donkey', 'fish']
'''

 

 

We invite the reader to try adding elements to a list below to visualize how a list will grow when appending elements to it. 

 


 

Original List of Animals:

 

 

 

 

List of Animals After Appending Item:

 


 

 

 

Remove Element from a List

 

Removing an element from a Python list involves deleting the element from the list, which causes the remaining elements to shift to fill the empty space. There are different ways to remove elements from a list, depending on the specific requirement.

 

Here are some common methods to remove elements from a Python list:

 

  1. Using the remove() method: This method removes the first occurrence of a specific value from the list. You need to specify the value to be removed as an argument to the remove() method. For example: my_list.remove('value').

  2. Using the del statement: The del statement allows you to remove an element at a specific index or a range of elements from a list. For example: del my_list[index] or del my_list[start:end].

 

It's important to note that removing an element from a list alters the indices of the subsequent elements, so be cautious when removing elements in a loop or when maintaining the order of elements is critical.

Remember to consider the specific requirements of your code and choose the appropriate method for removing elements from your list.

 

letters = ['a', 'b', 'c', 'd', 'e']

letters.remove('a')
print(letters)

'''

['b', 'c', 'd', 'e']

'''

 

Try the interactive exercise below. 

 


 

Original List of Letters:

 

 

 

 

 

List of Letters After Removing Element:

 

 

 


 

Notice that if you try to remove an element that is not present in the list you will get an error ValueError: list.remove(x): x not in list 

 

Pop Element from a List

 

in the context of lists 'popping' refers to the act of removing the last element from the list. When you 'pop' an element from a list, it is taken out of the list and returned as a result. 

 

Take the list of locations we have previously used as an example shown below. 

 

places = ['London', 'Paris', 'New York', 'Rome', 'Madrid']


popped_element = places.pop()

print(f'popped element is  {popped_element}')

print(f'places list after popping = {places}')

'''
popped element is  Madrid
places list after popping = ['London', 'Paris', 'New York', 'Rome']

'''

 

 

Try the interactive example below 

 

 


 

Original List

 

 

 

 

Popped Element:

 

List After Popping:

 

 

 


 

 

If you pop as many times as there are elements in the list, naturally you will be left with an empty list and python will return IndexError: pop from empty list

 

 

 

Inserting into a list

 

Inserting into a list is very similar to appending to a list that we have previously discussed. They are both methods to add an element to a list, however, they differ in the index position of where the new element is added. Below we show how they can be made to work in the same way. 

 

Note we make use of the len() function we have previously discussed in this article to return the number of elements contained within the list, and insert the new element 6 at the end of the list to replicate the append() behavior. 

 

nums = [1, 2, 3, 4, 5]

nums.append(6)

print(nums)

nums=[1, 2, 3, 4, 5]

nums.insert(len(nums), 6)

print(nums)


'''
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]

'''

 

Lets take another example where we insert in to the 0th  index of a list. 

 

places = ['London', 'Paris', 'New York', 'Rome', 'Madrid']

places.insert(0, 'Moscow')

print(places)

'''
 ['Moscow', 'London', 'Paris', 'New York', 'Rome', 'Madrid']
'''

 

 

Use the interactive exercise below to see how the elements and indexing of the list evolves as we insert new elements. 

 

 


Original List of Elements:

 

 

 

 

 

 

List of Elements After Insertion:

 

 


 

 

 

 

 

 

 

 

 

 

 

 

 


Join the discussion

Share this post with your friends!