CMU 15-110: Principles of Computing
1d Lists


  1. Creating Lists
  2. List Functions
  3. Accessing Elements
  4. Finding Elements
  5. Adding Elements
  6. Removing Elements
  7. Swapping Elements
  8. Looping Over Lists
  9. Copying Lists
  10. List Aliases
  11. Sorting Lists
  12. Some Worked Examples Using Lists

  1. Creating Lists
    print('Empty lists:') a1 = [ ] a2 = list() print(' ', a1, a2) print('Non-empty lists:') a3 = [2, 3, 5, 7] a4 = ['mixed types', True, 42] print(' ', a3, a4) print('Variable-length lists:') a5 = [42] * 10 print(' ', a5) print('Converting non-lists to lists:') a6 = list(range(5)) a7 = list('yes!') print(' ', a6, a7)

  2. List Functions
    a = [ 2, 3, 5, 2 ] print('a = ', a) print('len =', len(a)) print('min =', min(a)) print('max =', max(a)) print('sum =', sum(a))

  3. Accessing Elements
    a = [2, 3, 5, 7, 11, 13] print('Indexing works just like strings:') print(' a[0] =', a[0]) print(' a[-1] =', a[-1]) print('Slicing also works just like strings:') print(' a[1:3] =', a[1:3]) print(' a[3:] =', a[3:])

  4. Finding Elements
    a = [ 2, 3, 5, 2, 6, 5, 5, 7, 5 ] print('in, not in, count, and index all work just like strings:') print(' ', 3 in a) print(' ', 3 not in a) print(' ', a.count(5)) print(' ', a.index(5))

  5. Adding Elements
    • Using append is destructive (modifies the list)
      a = [ 2, 3 ] a.append(7) print(a)

    • Using + is non-destructive (creates a new list)
      a = [ 2, 3 ] b = a + [ 7 ] print(a) print(b)

  6. Removing Elements
    • Using remove
      a = [ 2, 3, 5, 4, 5 ] print('a =', a) a.remove(5) print("After a.remove(5), a=", a) a.remove(5) print("After another a.remove(5), a=", a)

    • Using pop
      a = [ 2, 3, 4, 5 ] print('a =', a) print('pop with no argument removes (pops) the last value:') v = a.pop() print(' We just popped:', v) print(' And now a =', a) print('pop with an argument removes the value at that index:') v = a.pop(1) print(' We just popped:', v) print(' And now a =', a)

  7. Swapping Elements
    • Failed swap
      a = [ 2, 3, 5, 7 ] print('a =', a) a[0] = a[1] a[1] = a[0] print('After failed swap of a[0] and a[1]:') print(' a=',a)

    • Swap with a temp variable
      a = [ 2, 3, 5, 7 ] print('a =', a) temp = a[0] a[0] = a[1] a[1] = temp print('After swapping a[0] and a[1]:') print(' a=',a)

  8. Looping Over Lists
    • Looping over items
      a = [ 2, 3, 5, 7 ] print('Here are the items in a:') for item in a: print(item)

    • Looping over indexes
      a = [ 2, 3, 5, 7 ] print('Here are the items in a with their indexes:') for i in range(len(a)): print('a[', i, '] =', a[i])

  9. Copying Lists
    print('Use (a + [ ]) to copy a list:') a = [2, 3] b = a + [ ] # creates a copy of a a[0] = 42 print(a) print(b)

  10. List Aliases
    • Aliases example:
      # Create a list a = [ 2, 3, 5, 7 ] # Create an alias to the list b = a # We now have two references (aliases) to the SAME list a[0] = 42 b[1] = 99 print(a) print(b)

    • Copies are not aliases:
      # Create a list a = [ 2, 3, 5, 7 ] # Create a COPY of the list b = a + [ ] # creates a copy of a # These are not aliases -- changes to one do not affect the other a[0] = 42 b[1] = 99 print(a) print(b)

    • Function parameters are aliases:
      def f(a): a[0] = 42 a = [2, 3, 5, 7] f(a) print(a)

  11. Sorting Lists
    • Using sort is destructive (modifies the list)
      a = [ 7, 2, 5, 3, 5, 11, 7 ] a.sort() print(a)

    • Using sorted is non-destructive (creates a new list)
      a = [ 7, 2, 5, 3, 5, 11, 7 ] b = sorted(a) print(a) print(b)

  12. Some Worked Examples Using Lists
    • The Locker Problem
      def lockerProblem(lockers): isOpen = [ False ] * (lockers+1) students = lockers for student in range(1,students+1): for locker in range(student, lockers+1, student): isOpen[locker] = not isOpen[locker] openLockers = [ ] for locker in range(1, lockers+1): if isOpen[locker]: openLockers.append(locker) return openLockers print(lockerProblem(2000))

    • Anagrams
      def letterCounts(s): counts = [0] * 26 for c in s.upper(): if (c.isalpha() == True): counts[ord(c) - ord('A')] += 1 return counts # Here are two very different ways to solve isAnagram: def isAnagram(s1, s2): return (letterCounts(s1) == letterCounts(s2)) def isAnagram(s1, s2): return sorted(s1.upper()) == sorted(s2.upper()) def testIsAnagram(): print('Testing isAnagram()...') assert(isAnagram('', '') == True) assert(isAnagram('abCdabCd', 'abcdabcd') == True) assert(isAnagram('abcdaBcD', 'AAbbcddc') == True) assert(isAnagram('abcdaabcd', 'aabbcddcb') == False) print('Passed!') testIsAnagram()