List methods (functions)

5.2. List methods (functions)#

Lists supports the following methods:

  • append(value) - add an element to the end of a list

  • insert(index, value) - insert an element to the list at the specified location

  • remove(value) - remove the first matching value from a list

  • pop() - remove the last element in the list; also returns the value; you can save this to another variable

  • pop(index) - remove the element at specified index in the list; also returns the value; you can save this to another variable

  • clear() - empty the list

  • index(element) - return position of first matching element

  • count(element) - return the number of elements in the list that match element;

  • sort() - sort the list in place

  • reverse() - reverse the list in place

grades = ['A', 'B', 'C']
grades.append('D')
print(grades)
['A', 'B', 'C', 'D']
grades = ['A', 'B', 'C']
grades.insert(3, 'F')
print(grades)
['A', 'B', 'C', 'F']
  • if the insert index is greater than the length of the list, the value will be added to the end of the list.

grades = ['A', 'B', 'C']
grades.insert(10, 'F')
print(grades)
['A', 'B', 'C', 'F']
grades = ['A', 'B', 'C']
grades.insert(0, 'F') # insert at beginning
print(grades)
['F', 'A', 'B', 'C']
grades = ['A', 'B', 'A', 'C']
grades.remove('A')
print(grades)
['B', 'A', 'C']
grades = ['A', 'B', 'C', 'D', 'F']
grades.pop() # deletes the last element in list and returns it 
print(grades)
grades.pop(0) # deletes the first element in list and returns it
print(grades)
grades.pop(2) # deletes the third element in list and returns it
print(grades)
['A', 'B', 'C', 'D']
['B', 'C', 'D']
['B', 'C']
grades = ['A', 'B', 'C']
grades.clear()
print(grades)
[]
grades = ['A', 'C', 'B', 'C']
print(grades.index('C'))
1
grades = ['A', 'C', 'B', 'C']
print(grades.count('C'))
2
grades = ['A', 'C', 'B', 'C']
grades.sort()
print(grades)
['A', 'B', 'C', 'C']
grades = ['A', 'B', 'C']
grades.reverse()
print(grades)
['C', 'B', 'A']