Arrays & Lists

Chapter 6

Note: This page is a work-in-progress#

In this chapter, we are going to look at a data structure you will be using extensively - arrays (called lists in Python).

Lists can comprise any data types (e.g. int, string or even other List types). Lists are similar to strings in the way that they are accessed by the index.

list_one = [1,2,3,4,5]
# prints 3

In this example, we are accessing index 2 of the list. Since the index starts from 0, at index 2, we have the element 3.

Similarly, we can iterate over lists using the for loop:

list_two = ['a','b','c']
for character in list_two:
# prints:
# a
# b
# c

Useful Methods for Lists in Python#

The below table has a few useful examples of methods we can use in Python lists. a refers to a list in the below methods.

a.append(x)Appends x to the end of the list
a.count(x)Counts how many times x appears in the list
a.remove(x)Remove x from list
a.reverse()Reverse the order of the list
Sort the list in ascending order, add reverse=True for descending order