Lists are a special variable type that allows us to hold many elements within a single variable name. This allows us to easily access and manipulate sets of data, instead of just single pieces of data. To get started, let’s take a look as an example of how we can create a list in Python.
Here we create a list, and we give it three strings of text, done by writing list_example = [“Test”,Test2”,”Test3”]. Once this is done, we print the items that are in the list. You’ll notice that the prints have square brackets with numbers inside of them. This indicates which item in the list we are wanting to access. List_example would be the first element in the list (Test1), list_example would be the second element, and so on. To better understand exactly how our list is being stored, take a look at the diagram below.
You can see that each item is separated by index. We start at index
In this example, we declare an empty list, and ask the user for three inputs to be appended to the list. After this, we print the three inputs that were provided. Note that the first input will be displayed first, since the first input will be placed at the first index of the list.
If we want to alter an element at a given index, we can reference it directly using its index, similar to how we are printing the values.
In this example, we create a list with three elements, 1,2,3. We then replace the value at the first index with the number 5, and output the result. After changing the value at index 0, we would have a list with values 5,2,3. We can also reference elements from the opposite end of the list using negative numbers. For instance, list_example[-1] would give us a value of 3, since index -1 would be the last element in the list.
With this information, you now have a basic understanding of how lists work in Python. Lists can be applied in a number of different ways, and are especially helpful when combined with repetition structures such as loops.