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?

In Python, a nested list is a list that contains other lists as its elements. Nested lists are a powerful way to represent and work with structured data, such as matrices, tables, or hierarchical data. In this section, we’ll explore how to create, access, and manipulate nested lists with code examples.

Creating Nested Lists

Creating a nested list is as simple as placing one or more lists inside another list. Here’s how you can create a basic nested list:

Python List

This creates a 2D list or a matrix.

Accessing Elements in Nested Lists

To access a specific element in a nested list, you can use multiple square brackets to navigate through the levels of nesting. For example, to access the element 5 in our nested_list, you would use:

Python List

Iterating through a nested list often requires nested loops. You can use a for loop within another for loop to iterate through each element. Here’s an example that prints all elements in the nested_list:

Python List

Modifying Nested Lists

You can modify the values in a nested list just like in a regular list. For instance, let’s change the 6 in nested_list to 60:

Python List

You can add or remove entire sublists from a nested list. To add a new sublist at the end:

Python List

To remove a sublist:

Python List

List Comprehensions with Nested Lists

List comprehensions can be used to perform operations on each element in a nested list. For example, let’s create a new nested list where each element is squared:

Python List

Practical Example: Matrix Transposition

Matrix transposition is a common operation with nested lists. It switches the rows and columns of a matrix. Here’s a Python function to transpose a nested list:

Python List

This code takes a nested list as input and returns its transpose.

Working with nested lists is essential for handling structured data effectively in Python. Whether you’re dealing with matrices, tables, or more complex hierarchical data, understanding how to create, access, and manipulate nested lists is a valuable skill for data manipulation and analysis.

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.

Other Articles on the Topic of Python Lists

  • 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.

Tags:
Cookie Consent with Real Cookie Banner