← Back Peter

Lesson 2: Peter’s Treasure List

Why?

A list holds many things. We can add and pick items by number spots.

What to type

  • Make chest = ["ruby", "diamond"]
  • Add: chest.append("sapphire")
  • Print first & last: print(chest[0], chest[-1])
⭐ Stars: 0
🐞 Bugs: 0

Go to Practice →



    
Hint

Square brackets [ ] are a treasure chest. chest[0] is the first item; chest[-1] is the last.

from js import document, localStorage, window import sys, io START = '''# A treasure chest is a list (like a row of boxes) chest = ["ruby", "diamond"] # add a new gem chest.append("sapphire") # print first and last print(chest[0], chest[-1]) # should show: ruby sapphire ''' SOLN = '''chest = ["ruby", "diamond"] chest.append("sapphire") print(chest[0], chest[-1]) ''' def gi(k): v = localStorage.getItem(k) try: return int(v) if v is not None else 0 except: return 0 def setb(stars=None, bugs=None): if stars is not None: localStorage.setItem('stars', str(stars)) if bugs is not None: localStorage.setItem('bugs', str(bugs)) document.getElementById('stars').textContent = f'⭐ Stars: {gi("stars")}' document.getElementById('bugs').textContent = f'🐞 Bugs: {gi("bugs")}' def run(evt): src = document.getElementById('editor').value out_el = document.getElementById('out') ns = {} f = io.StringIO() try: old = sys.stdout; sys.stdout = f try: exec(src, ns) finally: sys.stdout = old output = f.getvalue() assert 'chest' in ns and isinstance(ns['chest'], list), "Make a list named chest." assert ns['chest'][0] == "ruby", "First item should be 'ruby'." assert ns['chest'][-1] == "sapphire", "Last item should be 'sapphire'." out_el.textContent = (output or "") + "All checks passed! ⭐" setb(stars=gi('stars')+1) try: window.confetti() except: pass except Exception as e: out_el.textContent = "Bug found: " + str(e) setb(bugs=gi('bugs')+1) document.getElementById('run').addEventListener('click', run) document.getElementById('fill-start').addEventListener('click', lambda e: setattr(document.getElementById('editor'), 'value', START)) document.getElementById('fill-solution').addEventListener('click', lambda e: setattr(document.getElementById('editor'), 'value', SOLN)) if not document.getElementById('editor').value: document.getElementById('editor').value = START setb()