Tutorials on Advanced Math and Computer Science Concepts

# Lists in Python

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[0] would be the first element in the list (Test1), list_example[1] 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 0, and increment by 1 for each item that is in the list. For most concepts related to programming, we start counting at 0 by convention, so this is something to make sure to be aware of. From this short example, we see how we can create a list and access elements inside of the list. We can also add elements to the list using a method call append.

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.