Lists are used to store multiple variables in only one variable, very similar to how an array would function in Java. However, lists in Python are a lot more flexible in how they are able to operate.
Below is an example of the declaration and instantiation of a list in Python:
cars = ["Ford", "Mazda", "Honda", "Toyota"]
In Python, you are allowed to use multiple types of variables because a list in Python isn't locked to only one variable type like in Java.
data = ["red", True, 23, 1.625]
A specific index can be accessed in the same way that values in Java are accessed. The following code prints the first value in the cars list as well as the 2nd, 3rd, and 4th terms.
print(cars[0])
print(cars[1:3])
A list in Python be printed in its entirety by printing the name of the list.
print(cars)
Methods for Lists
The nice thing about lists in Python is that they are extendable and aren't set to a specific number of values. A value can be inserted into the list using .insert. The code below adds the value "Nissan" to the 3rd index of the list.
cars.insert(3,"Nissan")
Values can be added onto the end of a list by using the .append method.
cars.append("Chevrolet")
Indexes can also be removed from a list by using .remove.
cars.remove(3)
A string can be split and turned into a list by using .split. By default this method splits the string based on each space, but this can be changed to any character.