So far in this course, we have examined integers and strings as examples of data structures (although we may not have specifically referred to them by that name). In this lesson, we will explore another data structure called lists - which are arguably one of the most important data structures in the Python programming language.
What Are Lists
Lists are recognizable because they are created with square brackets. The elements within a list are separated by commas. You can see your first example of a list below:
The elements within a list can be accessed by passing in the element's index using square brackets. Remember, Python is zero-indexed, so the first element is accessed by index 0, the second element is accessed by index 1, and so on.
Unlike the other two data structures that we have seen so far - integers and strings - lists contain other elements, which causes them to have unique properties.
First of all, lists do not need to contain all of the same data types within them. Lists to not need to contain only integers or only strings, as an example.
Instead, lists can contain a variety of different element types:
More generally, lists can be contained within other lists - and this trend can continue on indefinitely. A list contained within another list is called a nested list. Some of the most unreadable code I have ever encountered has contained many levels of nested lists.
An example of a nested list with 1 layer is shown below:
An example of a nested list with 3 layers is shown below:
As you can imagine, nested lists can quickly become extremely complex when you start to involve multiple layers. Their readability can be improved by spreading them out on different lines, like this:
We'll now explore some of the most important methods that can be applied to lists before concluding this lesson.
How To Calculate The Length Of A List
We calculate the length of a list in the same way that we calculated the length of a string in our last lesson:
The last list method that we'll discuss will allow us to add one list to the end of another. This is similar to string concatenation that we discussed earlier in this course. The method of choice for this problem is .extend().
In this lesson, we explored lists - one of the most important data structures in Python. In the next lesson of this course, we will work through practice problems related to lists to solidify the information presented in this lesson.