Python Lists

Lists in Python can contain multiple values of varying data types. This is different from other languages, such as Java and C#, where the values are restricted to being all of the same type.

The example below creates a list of strings called ‘names’, adds three names, then, using a ‘for’ loop, displays the names in the console.

names = []

names.append("George")
names.append("Bob")
names.append("Fred")

for name in names:
   print(name)

The output from this will be as follows.

George
Bob
Fred

As well as adding values individually after the list has been defined, it is also possible to add values at the same time as it is being defined. This combines the list declaration, together with the three statements that utilise the ‘append’ method, in to one single statement.

names = ["George", "Bob", "Fred"]

In order to add another name to the list it is just a case of repeating how “George”, “Bob” and “Fred” were added with the ‘append’ method.

names.append("Andrew")

This would add the name ‘Andrew’ to the end of the list. Alternatively, the name could be added to a specific location in the list using the ‘insert’ method and specifying the index position, as shown below, where the name is included in the list at the start. Note that lists are zero based, meaning that the first position in the list is zero and not one.

names.insert(0, "Andrew")

If the names were output to the console now using the above method the output would be as follows.

Andrew
George
Bob
Fred

If there is a requirement to add multiple items to the end of a list after it has been defined, this can be achieved by using the ‘extend’ method.

names.extend(["Tom", "David"])

Accessing items in a list can either be done with a ‘for’ loop, as shown above, or, if an individual item is required and the index value is known, then this can be used. The example below outputs the second item in the list to the console, which has an index of one.

print(names[1])

The index can also be used in conjunction with the ‘del’ function to remove an item from a list.

del names[1]

If the index is not known, then the actual value of the item to be removed can be used.

names.remove("Bob")

A further useful feature of a list is that it can be sorted, either in ascending or descending order.

names.sort()    # Ascending order.
names.reverse() # Descending order.

Whichever method is used to sort a list, a ‘for’ loop can then be used to display the items, as in the above example.