The Power of Lists:

  • Up until now, all our variables have had a specific type or object, streetNumber = 87, or name = “jean-luc picard”
  • Sometimes we want to hold multiple objects in one variable.
  • For example, if we wanted to list some of WCU’s residence halls including: Albright, Benton, Balsam, Noble, and Shining Rock
1wcuResidenceHalls might include: Albright, Benton, Balsam, Noble, and Shining Rock

What is a List?

  • A list is a collection of items in a particular order. You can make a list that includes the letters of the alphabet, the digits from 0-9, or the names of all the people in your family.
  • Because a list usually contains more than one element, it’s a good idea to make the name of your list plural.
  • In Python, square brackets [ ] indicate a list, and individual elements in the list are separated by commas.
    • Here’s a simple example of a list of residence halls:
python
1wcuResidenceHalls = ['albright', 'benton', 'balsam', 'noble']
2print(wcuResidenceHalls)

Output: Note that Python will return its representation of the list, including the square brackets:

1['albright', 'benton', 'balsam', 'noble']

Accessing Elements in a List:

  • We can access any item in a list by telling Python the position, or index, of the item desired. To access an element in a list write the name of the list followed by the index of the item enclosed in square brackets.
  • As example, let’s pull out the first dorm in the list wcuResidenceHalls:
python
1wcuResidenceHalls = ['albright', 'benton', 'balsam', 'noble']
2print(wcuResidenceHalls[0])

Output:

1albright