Change Contents of the Bubble
Welcome to CS1315. Click on the python to add comments.

Looking for the book? They have it at the Engineer's Bookstore at 748 Marietta St NW. Here is there website: http://www.engrbookstore.com/ - Monica

Hotspots: Slides and CodeTA CornerComments?AnnouncementsFAQStatic Webspace
View this PageEdit this Page (locked)Uploads to this PageHistory of this PageHomeRecent ChangesSearchHelp Guide

Midterm Exam 2 Review Fall 2003: Duplicate a List

Answers? Comments? Questions on Answers? Questions on Comments?

(Back to Fall2003 Midterm Review 2)



I ran this code. It gave me this error: You are trying to access a part of the object that doesn't exist.

def duplicateList(list):
  duplicteList = []
  i = 0
  for item in list[:]:
    duplicateList[i] = item
    duplicateList[i+1] = item
    index = i + 2
  print duplicateList
  return duplicateList


def duplicateList(list):
  duplicateList = []
  for entry in list:
    duplicateList.append(entry)
    duplicateList.append(entry)
  print duplicateList


this one works
ps - how the heck do you post code without losing your indents???

Use and
 tags.

See the FAQ page. Do you see why you got that error on the first one? When you duplicate the elements, you end up with twice as many elements. You can't make a list longer by referring to indices that don't exist yet. Mark Guzdial


will someone walk through this code and explain why it works? I don't understand what "duplicateList.append(entry)" is doing.

would this work also?

def duplicateList(list):
newlist = []
for item in list:
newlist = newlist + [item]+[item]
return newlist


list.append(something) puts something at the end of the list. So if the list were ["a","b","c"], doing list.append["d"] would give you ["a","b","c","d"] in the list. Mark Guzdial


Within the above programs the line: newlist = []
This is opening a new list, right?

It's setting "newlist" to an empty list, yes. Mark Guzdial



Link to this Page