Only registred users can make comments

Python - Data Structure Types - Lists

Python - Data Structure Types - Lists


Python lists are a data structure that allow you to store, manage, and manipulate collections of data.

They are a fundamental building block for many applications and are widely used in various programming domains.

In many other programming languages, like JavaScript, lists are commonly referred to as arrays.

In this blog post, we will dive into the basics of Python lists, from creating and initializing lists to performing common operations such as accessing, modifying, and manipulating the data stored within. We'll also explore some of the key features and functions that make lists a valuable tool for solving a variety of programming problems.

Whether you're new to Python or a seasoned programmer, this post will provide you with the knowledge and skills you need to effectively work with lists in your projects.

The list is the most commonly used data structure type in Python and is very similar to tuples and sets but has some fundamental differences.

Let's start by creating a simple list:

>>> cars = ['Porsche', 'Bmw', 'Audi', 'Volvo', '2021', 'Audi']

and then let's print it out:

>>> print(cars)
['Porsche', 'Bmw', 'Audi', 'Volvo', '2021', 'Audi']

A list is a data structure that allows you to store multiple items with the same or different content.

For example, you can have the same item, such as 'Audi', repeated multiple times in a list.

Lists in Python can also support different data types, such as integers, strings, floats, and more.

Each item in a list is assigned a unique index number, making it easy to access and manipulate individual elements.

You can perform operations such as updating, adding, replacing, and removing items in a list, as well as iterating through the list to process its elements.


What methods can we use with Python lists?Method - index()
Method - append()
Method - dunder method - __len__()

What methods can we use with Python lists?

Lists in Python offer a range of powerful features that make them a valuable tool for solving many programming problems. In this article, we will not cover all of the available features, but we'll take a look at some of the most useful ones.

To see the list of methods and attributes that are supported by lists, you can use the dir(list) command in Python:

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

We're going to cover a number of those methods supported by the list type.

Method - index()

In Python, each item in a list has both a positive and a negative index value. The positive index value starts from 0 and increases towards the end of the list, while the negative index value starts from -1 and decreases from the end of the list towards the beginning.


cars = ['Porsche', 'Bmw', 'Audi', 'Volvo', '2021', 'Audi']





With the index() function we got the index value of 2. 


Let's assume that '2021' in the index of 4 is wrong and we want to exchange it with a new car brand like Honda. Also, Audi with index of 5 is something we would like to replace with Peugeot since we already got Audi. 

cars = ['Porsche', 'Bmw', 'Audi', 'Volvo', '2021', 'Audi']

cars[4] = 'Honda'  # we are inserting a new item to index 4

cars[-1] = 'Peugeot' # we are using the negative index value to replace the value of index 5



['Porsche', 'Bmw', 'Audi', 'Volvo', 'Honda', 'Peugeot']

Now, let's slice the list a little bit. We want to get items from index 2 to 4.

But remember the following, you can define the starting index, ending index, and the steps.

my_list[start, stop, step]




['Audi', 'Volvo']

Let's reverse the list:



['Peugeot', 'Honda', 'Volvo', 'Audi', 'Bmw', 'Porsche']

The code print(cars[::-1]) prints the list cars in reverse order. The slicing syntax [::-1] is used to reverse the list.

The slicing syntax [start:end:step] allows you to extract a portion of a list by specifying the starting index (start), ending index (end), and the step size (step). The step size determines the increment between consecutive items in the sliced list.

In this case, the slicing syntax [::-1] starts at the end of the list (since start is not specified), ends at the beginning of the list (since end is not specified), and steps backwards by one item at a time (since step is -1). The result is the list cars reversed.

Method - insert()

With the insert() method, you can add a new item to a list at the desired position. Again, assume that we have the following list containing cars list:

Let's create the list assigning it to a variable:

cars = ['Porsche', 'Bmw', 'Audi', 'Volvo']

Now, if we want to insert a new car brand like Peugeot just after Audi, we'd need to use the insert() method that takes two arguments, position and the item itself.

cars.insert(3, 'Peugeot')

The code cars.insert(3, 'Peugeot') inserts a new item "Peugeot" into the list cars at index position 3.

The insert() method is a built-in method of Python lists that allows you to add a new item to the list at a specific index position. The first argument to the insert() method is the index position where you want to insert the new item, and the second argument is the item you want to insert. In this case, the item "Peugeot" is inserted at index position 3 in the list cars.

After executing this code, the list cars would look like this: ['Audi', 'BMW', 'Mercedes', 'Peugeot', 'Porsche']

This will push Volvo to the right, and our new item, Peugeot, will get an index of 3. 

 We can make a simple test by typing:



Method - remove()

The remove() method is another built-in method of Python lists that allows you to remove an item from the list. Unlike the append() method, which adds a new item to the end of the list, the remove() method requires you to specify the item you want to remove.

The remove() method operates on the actual item in the list, not its index. To remove an item from a list by index, you can use the del statement.

For example, if you have a list of cars:

 With remove() method, we need to specify the item name, it's not possible to specify the index. Example:


['Porsche', 'Bmw', 'Peugeot', 'Volvo']

The remove() method removes the first occurrence of the specified item in the list. In this example, the first occurrence of 'Audi' would be removed from the list, so the list would now be ['Porsche', 'Bmw', 'Peugeot', 'Volvo'].

Keep in mind that the remove() method only removes the first occurrence of the item, even if there are multiple instances of the same item in the list.

To remove all occurrences of an item, you can use a loop and the remove() method inside the loop.

Method - append()

With the append() function, we can add new elements to an existing list. In this example, we're going to add Peugeot to our list:

car_manufacturers = ['Porsche', 'Bmw', 'Audi', 'Volvo']


['Porsche', 'Bmw', 'Audi', 'Volvo', 'Peugeot']

Please be aware, with append() method, the item will be appended at the end of the list. If you want to select the positioning of the item, have a look at the insert() method. 

Method - dunder method - __len__()

With the len() method we can check how many items we have in our list. We can also use the dunder method called __len__() that will basically provide the same result.

>>> print(len(cars))
>>> print(cars.__len__()) ## dunder method

Method - sort()

Sorting our list based on the alphabetical order

>>> cars.sort()
>>> print(cars)
['2021', 'Audi', 'Audi', 'Bmw', 'Porsche', 'Volvo']

With reverse=True we can sort our list in a reversed order

>>> cars.sort(reverse=True)
>>> print(cars)
['Volvo', 'Porsche', 'Bmw', 'Audi', 'Audi', '2021']

You can also specify your own parameter with the key function and sort your list based on the parameter you pass.
The simplest example is to pass the built-in len() function and sort your list based on the length of each item. 

>>> cars.sort(key=len)
>>> print(cars)
['Bmw', 'Audi', 'Audi', '2021', 'Volvo', 'Porsche']

In the following example, we will create a list with three dictionary items. 
Then we will create a simple function that is returning a Model based on dict get() method. 

By using key=get _model, we are passing the calling the function and sorting our list based on Model:

cars = [
{'Brand': 'Volvo', 'Model': 'S90', 'Engine': 'T8'},
{'Brand': 'Audi', 'Model': 'A6', 'Engine': 'TDI'},
{'Brand': 'Peugeot', 'Model': '508', 'Engine': 'BlueHDI'},
{'Brand': 'Alfa Romeo', 'Model': 'Spider', 'Engine': '2.0'},

def get_model(item):
    return item.get('Model')


for i in cars:

Output (sorted based on the car model):

{'Brand': 'Peugeot', 'Model': '508', 'Engine': 'BlueHDI'}
{'Brand': 'Audi', 'Model': 'A6', 'Engine': 'TDI'}
{'Brand': 'Volvo', 'Model': 'S90', 'Engine': 'T8'}
{'Brand': 'Alfa Romeo', 'Model': 'Spider', 'Engine': '2.0'}

Method - sum()

In Python, if a list contains only integer or float data types, it's possible to find the sum of its elements. Here's an example of how to do so with a list of prices:

cost = [14.99, 12.99, 19.99, 29.99]




The code creates a list named "cost" containing prices of different items.

The sum() function is then used to calculate the total sum of the values in the list. The final line of code prints out the sum of the values in the list "cost".

The output is 77.96 (the sum of all the prices in the list).

Please remember, if you would have a string in your list, you would get the following error:

TypeError: unsupported operand type(s) for +: 'float' and 'str'



Lists are a widely used data structure in Python and are extremely versatile. They are often returned when making API calls and are a common format for handling various types of data. To fully take advantage of the power of Python, it's important to have a good understanding of lists.

Our Python Fundamentals course will go in-depth on the topic of lists and provides a comprehensive understanding of their use.

About the Author

Aleksandro Matejic, a Cloud Architect, began working in the IT industry over 21 years ago as a technical specialist, right after his studies. Since then, he has worked in various companies and industries in various system engineer and IT architect roles. He currently works on designing Cloud solutions, Kubernetes, and other DevOps technologies.

In his spare time, Aleksandro works on different development projects such as developing, a blog and learning platform launching in 2022/2023. In addition, he likes to read and write technical articles about software development and DevOps methods and tools. You can contact Aleksandro by visiting his LinkedIn Profile.