# CMU 15-110: Principles of Computing 1d Lists (Part 2)

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

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

2. 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 = 42 b = 99 print(a) print(b)

• Copying lists:
print('Use (a + [ ]) to copy a list:') a = [2, 3] b = a + [ ] # creates a copy of a a = 42 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 = 42 b = 99 print(a) print(b)

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

3. 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)

4. Example: Anagrams
def letterCounts(s): counts =  * 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()