Today, we will talk about what are lists and tuples and why we need them.
A list is simply a datatype, like an integer (int), but one that can store multiple values in one variable, where the values can be of any type. For example, let us create a program that creates a list and then prints it out. To start, create a new program:
And place the following code:
values=[1,2,3,4,5]
print(values)
Once done, run the program:
As we can see, the print(values) statement shows the contents of the list, as well as the list formatting.
Lists can also contain other types of values, and values can even be of different datatypes at the same time, including lists:
As we can see, the list is still valid.
To access specific elements in a list, we use the list index feature. we access an element using the following syntax: list_name[element_index]. However, the most interesting thing about lists is that the first element in lists have an index of zero. That's right, zero. This is because when computers were first created with C, they had to start counting from zero.
To print out the first element, add the following line:
print(values[0])
Once done, run the program:
Note: I have commented out the print(values) line to avoid confusion.
As we can see, the program gave an output of 34.2, the first element in the list.
We can also access other elements too with different values of indices, access a range of elements using index ranges, and even use negative indices (In Python). Just be sure that the positive indices are less than the length of the list. Here is an example of using an index range and a negative index:
And here is an example of using an index which is out-of-bounds:
If you need to access an element inside a list that serves as an element in another list, just use the same syntax but with two index values passed (That is, list_name[index1][index2]) This can be done any number of times, that is, the general syntax to access elements inside lists inside lists is list_name[index1][index2]...[indexN]. An example:
A tuple acts exactly the same way as lists:
The only difference is that tuples are immutable, while lists are mutable. Meaning, once defined, a tuple's contents cannot be changed by another piece of code in the program, while a list's contents can be changed. Sometimes a tuple is beneficial if it is being used to store permanent data.
Lists are useful for storing data that can and/or needs to be changed and tuples are useful for storing data that cannot and does not need to be changed.
Note: To update a value in a list, use the following syntax:
list_name[list_index]=new_value
Note 2: To add a new value at the end of a list, use the following syntax:
list_name.append(new_value)