Write a Python function called Copy List(myList) that takes as input a list. The
ID: 3796141 • Letter: W
Question
Write a Python function called Copy List(myList) that takes as input a list. The function should make a copy of the provided list and return the copy making sure to leave the original list unchanged. Note that for this program you are not allowed to use slicing and must access the list elements using indexing. Write a Python function called SwapElement(myList, index1, index2) that takes as input a list and two integer numbers. The function should first make sure that the two integer numbers are valid index values to the list and upon verification of this, the function should swap the two entries in the list specified by the index values. This function should not return anything.Explanation / Answer
def CopyList(myList):
copyL = []
for i in xrange(0, len(myList)):
copyL.append(myList[i])
return copyL
def SwapElement(myList, index1, index2):
if (index1 >= 0) and (index2 >= 0) and (index1 < len(myList)) and (index2 < len(myList)):
myList[index1], myList[index2] = myList[index2], myList[index1]
l = [1,2,3,4,5,6,7,8]
m = CopyList(l)
print m
print l
SwapElement(l, 1,3)
print l
# pastebin link incase indentation mess up: http://pastebin.com/LT8FCLhq
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.