So far you have used variables to store information that you will need throughout your program. Let’s imagine that you have a program that will require you to store 100 pieces of information. It will be very tedious to create 100 separate variables. Instead, for situations like this we use lists.
A list is a sequential collection of Python data values, where each value is identified by an index. The values that make up a list are called its elements. Lists are similar to strings, which are ordered collections of characters, except that the elements of a list can have any type and for any one list, the items can be of different types.
There are several ways to create a new list. The simplest is to enclose the elements in square brackets ( [
and ]
).
my_first_list = [ ]
This list will be able to store as many pieces of information as you want. You can initialize the list with your own information or you can add on to the list later on in your program, or both!
Here is a list that is created with three initial values:
my_list = [500, 1999, 4]
We can add more values to this list using the append function.
my_list.append(800) my_list.append(900)
Our list would now store the numbers 500, 1999, 4, 800 and 900.