The power of lists
You will now look at the first type of data structure in Python: lists.
A list is a type of container in Python that is used to store multiple datasets at the same time. Python lists are often compared to arrays in other programming languages, but they do a lot more.
The following figure shows a list of fruits, along with their respective indices:
Figure 2.2 – A Python list with a positive index
A list in Python is written within square brackets, [ ]
. Each element in the list has its own distinct index. The elements in a list have a finite sequence. Like other programming languages, the index of the first item of a list is 0, the second item has an index of 1, and so on. This has to do with how lists are implemented at a lower programming level, so do take note of this when you are writing index-based operations for lists and other iterable objects.
You will now look at the different ways that lists can be useful.
Exercise 21 – working with Python lists
In this exercise, you will learn how to work with a Python list by coding and creating a list and adding items to it. For example, this could prove useful if you have to use a list to store the items that are in a shopping cart:
- Open a new Jupyter Notebook.
- Now, enter the following code snippet:
shopping = ["bread","milk", "eggs"]
print(shopping)
The output is as follows:
['bread', 'milk', 'eggs']
Here, you created a list called shopping
with bread
, milk
, and eggs
inside it.
Since a list is a type of iterable in Python, you can use a for
loop to iterate over all of the elements inside a list.
- Now, enter and execute the code for a
for
loop and observe the output:for item in shopping:
print(item)
The output is as follows:
bread
milk
egg
Note
Python lists are different from arrays used in other languages, such as Java and C#. Python allows mixed types in a list – that is, int
and string
.
- Now, use a
mixed
type of data within the list’s content and enter the following code in a new cell:mixed = [365, "days", True]
print(mixed)
The output is as follows:
[365, 'days', True]
But you might be wondering, in that case, shouldn’t we be allowed to store a list of lists inside a list? We will take an in-depth look at nested lists, which can be used to represent complex data structures, after the next section.
In this exercise, you were introduced to the basics of Python lists.
Now, let’s see what list methods are available in Python.