Skip to content

Python Lists – easily explained!

Python Lists are used to store multiple items in a single variable. They are one of a total of four data structures that are pre-installed in Python. Besides the list, they also include the tuple, the set, and the dictionary.

We define a Python List by writing the elements in square brackets. We can store elements with different data types in a list. A second way to create lists is by calling the “list()” function. For this, the elements must be written in double-round brackets. However, this way of writing is used rather rarely.

Python List

How to retrieve list items?

The elements of a Python List have an index that determines the order for each element. The individual elements of a list can be called via their corresponding index. Here, of course, it must be noted that our computer starts counting at 0. So the first element of the list has an index of 0.

Python List

Using the index it is also possible to call the last element of the list without knowing the length of it and thus the concrete index. With the help of the negative index, we can call objects from the list starting from the back. With this counting method, we start at 1 and not at 0.

Python List

If we want to query not only individual elements of the list but a complete range, we can define it by specifying the start and end index. It should be noted that the start index is part of the output, while the end index is not.

Python List

It is noticeable here that the query of a list range always returns a list as a result, even if the Python List has only one element.

This query can also be executed without specifying the end index. There are two possibilities for this:

Python List

In the first option, square brackets contain the starting index and then a colon. In our example, this returns the second element and all other elements of the list that come after the second element, no matter how many elements still follow, i.e. “Tokyo”, “Montreal” and “Berlin”.

In the second variant, the square brackets contain first a colon and then the initial index. In this case, we get from the Python List all the elements that come before the third element of the list, that is, “New York” and “Tokyo”.

As an aid for these types of queries, one can use the following, small algorithm:

  1. Place the cursor in front(!) of the element defined by the number.
  2. If the colon is behind the number, i.e. to the right of it, then the result consists of a list with all elements to the right of the cursor. If the colon is in front of the number, i.e. to the left of it, then the result consists of a list of all elements to the left of the cursor.

For our first query “list_1[1:]” we put the cursor in front of the second element, i.e. in front of “Tokyo”. Since the colon is to the right of the 1, we must use all the elements to the right of the cursor in the result. Thus the result consists of a Python list with the elements “Tokyo”, “Montreal” and “Berlin”.

How to change list items?

If we want to change single or multiple elements of a Python list, we call them as described above and simply redefine their value.

Python List

At the same time, we can also insert an element anywhere in the list using the “insert()” method without changing any existing entry. The index of the following values will increase by 1 accordingly. If we simply want to append an element to the end of the list, we can do that with the “append()” method.

Python List

Of course, we can also remove values from a Python list instead of overwriting them. For this purpose there are the methods “pop()” and “remove()”. The difference between the methods is that “pop()” takes the index as input and “remove()” takes the concrete element.

Python List

How to sort elements in a list?

Although the elements are sorted in the list, you can sort them alphabetically or numerically. However, this changes their index, i.e. the order within the list:

Python List

The order in a Python list can also be reversed, i.e. that it is sorted from Z to A or from large number to small number. For this you only need the additional parameter “reverse = True”:

Python List

However, the sorting algorithm only works if the Python list consists of data with a uniform data type. A mixture of numbers and strings leads to a so-called “TypeError”:

Python List

What are the differences between NumPy arrays and Python lists?

Depending on the source, there are several, fundamental differences between NumPy arrays and Python lists. Among the most commonly mentioned are:

  • Memory Consumption: Arrays are programmed in such a way that they occupy a certain part of the memory. All the elements of the array are then located there. The elements of a list, on the other hand, can be far apart in memory. As a result, a list consumes more memory than an identical array.
  • Speed: Arrays can also be processed much faster than lists due to their lower memory consumption. This can make a significant difference for objects with several million elements.
  • Functionality: Arrays offer significantly more functionalities, for example, they allow element-by-element operations, whereas lists do not.
Python List

How can you work with nested lists, i.e. a list of lists?

A list can not only consist of individual elements but can also contain lists. This so-called nested list is a powerful way of displaying multidimensional structures such as matrices, tables, or other hierarchical data. This section explains basic commands for working with nested lists.

Creating Nested Lists

Creating a nested list is simple and it can be defined in the same way as a normal Python list. However, the elements used are not individual elements, but other lists.

Python List

This created list can be understood as a representation of a matrix with three rows and three columns.

Accessing Elements in Nested Lists

To query elements from this Python list, you can work with indexes in the same way as we have already seen. The only difference is that one index is not enough, as this index refers to a list. Therefore, at least a second index is required to query an element in the inner list.

For example, to get the element 5 we need the second element from the second list, so we need the index 1 twice, which we can query with square brackets.

Python List

To iterate through all elements of a nested Python list, we also need several nested loops. To be able to output each element of nested_list, two for loops are required, the first iterates through all sublists, while the second iterates through all elements in the sublist and then outputs them.

Python List

Modifying Nested Lists

As with regular Python lists, individual elements in a nested list can also be overwritten by specifying the index. However, this again requires two indexes to access an element and not to overwrite an entire sublist.

The third element in the second sublist can be overwritten with the following command:

Python List

Another sublist, or another row of the matrix, can be added with the .append() statement.

Python List

The second sublist can be removed with the following command:

Python List

List Comprehensions with Nested Lists

List Comprehensions are generally used to perform operations on each element of a Python list. This can of course also be done with nested lists, with the difference that it also requires nested loops.

To square each element in the nested list, the following command can be used:

Python List

Practical Example: Matrix Transposition

With matrix transposition, the rows of the matrix become the columns of the transposed matrix and the columns of the original matrix become the rows of the transposed matrix. In Python, this can be implemented using nested lists and a list comprehension:

Python List

This function takes a nested list as input and returns a transposed matrix as output.

Working with nested Python lists is essential for handling structured and multidimensional data in Python. This can also be of crucial importance when working with data sets in the field of machine learning, for example, as it helps to manipulate data and analyze it efficiently.

What is the difference between a Pandas Series and a Python List?

At this point in the article, you might have gotten the impression that the Pandas Series and the Python List are two very similar data structures whose main difference is that the list can only use numeric indexes, while the Pandas Series also allows textual indexes.

The main difference between the Series and list is not in their functionality or structure but in their application possibilities. In the field of Data Science, the Series is mainly used as a preliminary stage for tabular data, which in turn are to be illustrated in diagrams. This means that the Series can be viewed in concrete terms.

The list, on the other hand, is used to temporarily store complex data structures, so it tends to stay in the background and serves as a tool for complex calculations. The main differences are mainly:

  • Homogeneity: A Pandas series requires all data elements to be of the same data type, while a Python list can contain elements of different data types.
  • Memory efficiency: Pandas series are more memory efficient than Python lists because they use NumPy arrays internally, which are more compact and faster for numerical computations.
  • Vectorization: Pandas series support vectorized operations that allow us to perform calculations on entire sequences of data at once, making data processing faster and more efficient. Python lists, on the other hand, do not support vectorized operations.

Which Python collections are available?

In Python, there are a total of four data types that are stored by default:

  • The list is an ordered collection of elements, which is changeable and can also contain duplicate elements.
  • The tuple is in effect a list, with the difference that it is no longer changeable. So no elements can be added or removed afterward.
  • The set does not allow duplicate entries. At the same time, the arrangement of the elements within the set is variable. The set itself can be changed, but the individual elements cannot be changed afterward.
  • Since Python version 3.7, a dictionary is an ordered collection of key-value pairs that can be changed. In the earlier versions, the dictionary is unordered.

This is what you should take with you

  • Python Lists can be used to store a collection of items in a Python variable.
  • The list is ordered and can be modified using commands.

Thanks to Deepnote for sponsoring this article! Deepnote offers me the possibility to embed Python code easily and quickly on this website and also to host the related notebooks in the cloud.

Anaconda Python

What is Anaconda for Python?

Learn the essentials of Anaconda in Python for efficient package management and data science workflows. Boost your productivity today!

Regular Expressions

What are Regular Expressions?

Unlock powerful text manipulation in Python with regular expressions. Master patterns, syntax, and advanced techniques for data processing.

Object-Oriented Programming / Objektorientierte Programmierung

What is Object-Oriented Programming?

Master Object-Oriented Programming concepts in Python with our beginner's guide. Learn to create reusable code and optimize your coding skills.

Plotly

What is Plotly?

Learn how to create interactive visualizations and dashboards with Plotly, a Python data visualization library.

Matplotlib

What is Matplotlib?

Visualize your data like a pro with Matplotlib: A comprehensive guide to the Python plotting library.

Debugging Techniques in Python

What are Debugging Techniques in Python?

Master Python debugging techniques: Reproduce, isolate, and resolve bugs with step-by-step examples. Enhance your coding skills now!

  • w3schools offer detailed examples of Python lists with the possibility to execute code snippets directly online.
Das Logo zeigt einen weißen Hintergrund den Namen "Data Basecamp" mit blauer Schrift. Im rechten unteren Eck wird eine Bergsilhouette in Blau gezeigt.

Don't miss new articles!

We do not send spam! Read everything in our Privacy Policy.

Cookie Consent with Real Cookie Banner