3.4

# Lists

Python has a data type for storing lists, imaginatively called List. A list can store a sequence of any other pieces of data of any types (integers, strings, booleans, etc.).

Note: Other programming languages might refer to lists as arrays. While they have a different name and their usage might also be different, conceptually they are the same.

You can create a list variable in Python in just the same way as any other variable: by giving it a name and assigning it a value. For a list, the value will be a sequence of elements to be put in the list, written between square brackets [] and separated by commas:

my_list = [1, 2, 3, 4, 5]


If you want to create an empty list, which you will append items to later in your program, you can use empty square brackets: [].

my_list = []


Note: Lists can contain all different types of data: integers, strings, and anything else. They can even contain other lists. (Lists of lists are very useful for storing tables of data, but that’s a subject for another course!)

• Create a list of names using the REPL.
names = ["martin", "laura", "hitesh", "caitlyn", "renee"]

• Using an index, as you did with a string, get the second name (index 1) from the list.
names[1]


A feature of lists in Python is that they can be changed after they have been created: you can append new elements to the end of the list, insert them in the middle, or remove them completely using the three functions append, insert and remove. (As these are special list functions, they are joined with a dot to the name of the list they apply to, as in the examples below. Technically functions of this kind are called “methods”.)

• Append a new name to the end of your list of names.
names.append("lauren")

• Check to make sure your new name has been appended to the end of your list.
names


• Next let’s use insert to put a new name in the middle of the list, by also using the index of where to insert the new name.
names.insert(2, "dan")

• Check to make sure that the names variable has been updated.

• As a last step let’s remove the name “martin” from the list.

names.remove("martin")


Lists are really powerful and are the cornerstone of how iteration is done in Python, so it is worth exploring them to make sure you have a good understanding of how they work. Make sure that you can explain how the append, insert and remove commands work in your own words.

Next let’s put all these ideas together and create a new program which uses lists to create a loop.