Index positions:

  • When accessing the last element in a list we can ask for the item at index –1. Similarly, the index –2 returns the second item from the end of the list, the index –3 returns the third item from the end…and so forth.
  • Accessing the Last Element in a List:
    • Ask for item at index –1.

Modifying Elements in a list:

  • Most lists you create will be dynamic, meaning you’ll build a list and then add and remove elements from it as your program runs.
  • The syntax for modifying an element is similar to the syntax for accessing an element in a list.
  • To change an element, use the name of the list followed by the index of the element you want to change, and then provide the new value you want that item to have.
  • Appending Elements to the End of a List:
    • The simplest way to add a new element to a list is to append the item to the list. When you append an item to a list, the new element is added to the end of the list. Using the same data as in the previous example, we’ll add the element ‘norton’ to the end of the list. In addition, we’ll assign the element value to a variable and use the print() function to display an output:
python
1wcuResidenceHalls = ['albright', 'benton', 'balsam', 'noble'] 
2print(wcuResidenceHalls)
3
4tooFar = 'norton'
5wcuResidenceHalls.append(tooFar)
6print(wcuResidenceHalls)
7print("\nThe Residence Hall, " + wcuResidenceHalls[-1].title() + ", is far away.")

Output:

1['albright', 'benton', 'balsam', 'noble']
2['albright', 'benton', 'balsam', 'noble', 'norton']
3    
4The Residence Hall, Norton, is far away.

Removing an Item Using the pop() Method:

  • Sometimes you’ll want to use the value of an item after you remove it from a list.
    • Example: In a web app, you might want to remove a user from a list of active members to a list of inactive members
  • The pop() method removes the last item in a list, but it lets you work with that item after removing it.
  • Below we pop a residence hall from the list of WCU residence halls:
python
1wcuResidenceHalls = ['albright', 'benton', 'balsam', 'noble']
2print(wcuResidenceHalls)
3
4poppedWcuResidenceHalls = wcuResidenceHalls.pop()
5print(wcuResidenceHalls)
6print(poppedWcuResidenceHalls)

Output:

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