Im having trouble with codehs swapping 9.5.6

This is the assignment: Use your knowledge of unpacking and identity to complete the function swap_lists. This function should take two lists as arguments and swap their values.

Your starter code calls your function like this: list_one = [1, 2, 3] list_two = [4, 5, 6] print "Before swap" print "list_one: " + str(list_one) print "list_two: " + str(list_two) swap_lists(list_one, list_two) print "After swap" print "list_one: " + str(list_one) print "list_two: " + str(list_two)

Note that the starter code will not run, since the function definition is empty! Hint: It won’t work to just do something like this: first, second = second, first You will instead need to use a control structure to swap individual elements in the lists!

This is my code: # swap_lists # ----- # This function takes two lists of equal length # as arguments and swaps their values. def swap_lists(first, second): if len(first) != len(second): print "Lengths must be equal!" return

 # Write your code here... for i in range(3): second[i] for i in range(3): first[i]= second[i]
list_one = [1, 2, 3]
list_two = [4, 5, 6]
print "Before swap"
print "list_one: " + str(list_one)
print "list_two: " + str(list_two)
swap_lists(list_one, list_two)
print "After swap"
print "list_one: " + str(list_one)
print "list_two: " + str(list_two)

What do I need to add for this to work?

2 Answers

after # write your code:

elif len(first)==len(second): for i in range(len(first)): first[i], second[i] = second[i], first[i]

 def swap_lists(first, second): f = [second, first] print("After swap") print("list_one: " + str(f[0])) print("list_two: " + str(f[1])) list_one = [1, 2, 3] list_two = [4, 5, 6] print("Before swap") print("list_one: " + str(list_one)) print("list_two: " + str(list_two)) swap_lists(list_one, list_two)

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like