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.
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.
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.
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.
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:
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:
- Place the cursor in front(!) of the element defined by the number.
- 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.
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.
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.
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:
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”:
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”:
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.
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.
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.
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.
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:
Another sublist, or another row of the matrix, can be added with the .append()
statement.
The second sublist can be removed with the following command:
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:
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:
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.
What are Python Modules?
Explore Python modules: understand their role, enhance functionality, and streamline coding in diverse applications.
What are Python Comparison Operators?
Master Python comparison operators for precise logic and decision-making in programming.
What are Python Inputs and Outputs?
Master Python Inputs and Outputs: Explore inputs, outputs, and file handling in Python programming efficiently.
How can you use Python for Excel / CSV files?
This article shows how you can use Python for Excel and CSV files to open, edit and write them.
How can you do Python File Handling?
Unlock the power of Python file handling with our comprehensive guide. Learn to read, write, and navigate files efficiently.
What are Python Loops?
Master Python loops: Learn `for` and `while` iterations, control statements, and practical uses in this comprehensive guide.
Other Articles on the Topic of Python Lists
- w3schools offer detailed examples of Python lists with the possibility to execute code snippets directly online.