paul@206 | 1 | l = [1, 2, 3] |
paul@221 | 2 | l.append("four") |
paul@304 | 3 | print len(l) # 4 |
paul@266 | 4 | print l[0] # 1 |
paul@266 | 5 | print l[1] # 2 |
paul@266 | 6 | print l[2] # 3 |
paul@266 | 7 | print l[3] # four |
paul@266 | 8 | print l[-1] # four |
paul@266 | 9 | print l[-2] # 3 |
paul@266 | 10 | print l[-3] # 2 |
paul@266 | 11 | print l[-4] # 1 |
paul@266 | 12 | print l # [1, 2, 3, "four"] |
paul@227 | 13 | |
paul@227 | 14 | t = (1, 2, 3, "four") |
paul@227 | 15 | l = list(t) |
paul@266 | 16 | print l # [1, 2, 3, "four"] |
paul@266 | 17 | |
paul@266 | 18 | try: |
paul@266 | 19 | print l[4] # should raise an exception |
paul@266 | 20 | except IndexError, exc: |
paul@266 | 21 | print "l[4]: failed with argument", exc.index |
paul@266 | 22 | |
paul@266 | 23 | try: |
paul@266 | 24 | print l[-5] # should raise an exception |
paul@266 | 25 | except IndexError, exc: |
paul@266 | 26 | print "l[-5]: failed with argument", exc.index |
paul@279 | 27 | |
paul@279 | 28 | print 1 in l # True |
paul@279 | 29 | print 4 in l # False |
paul@279 | 30 | print "four" in l # True |
paul@279 | 31 | print "one" in l # False |
paul@279 | 32 | print 1 not in l # False |
paul@279 | 33 | print 4 not in l # True |
paul@279 | 34 | print "four" not in l # False |
paul@279 | 35 | print "one" not in l # True |
paul@282 | 36 | |
paul@282 | 37 | print l.index(1) # 0 |
paul@282 | 38 | print l.index("four") # 3 |
paul@282 | 39 | |
paul@282 | 40 | try: |
paul@282 | 41 | print l.index(4) # should raise an exception |
paul@282 | 42 | except ValueError, exc: |
paul@282 | 43 | print "l.index(4): failed to find argument", exc.value |
paul@460 | 44 | |
paul@516 | 45 | # Test equality. |
paul@516 | 46 | |
paul@460 | 47 | print l == [1, 2, 3] # False |
paul@460 | 48 | print l == [1, 2, 3, "four"] # True |
paul@516 | 49 | |
paul@516 | 50 | # Test concatenation. |
paul@516 | 51 | |
paul@516 | 52 | a = [1, 2] |
paul@516 | 53 | a += [3, 4] |
paul@516 | 54 | print a # [1, 2, 3, 4] |
paul@516 | 55 | |
paul@516 | 56 | b = [5, 6] |
paul@516 | 57 | c = a + b |
paul@516 | 58 | print c # [1, 2, 3, 4, 5, 6] |
paul@516 | 59 | |
paul@516 | 60 | # Test removal. |
paul@516 | 61 | |
paul@516 | 62 | print c.pop() # 6 |
paul@516 | 63 | print c # [1, 2, 3, 4, 5] |
paul@516 | 64 | |
paul@516 | 65 | d = [] |
paul@516 | 66 | try: |
paul@516 | 67 | d.pop() # should raise an exception |
paul@516 | 68 | except IndexError, exc: |
paul@516 | 69 | print "d.pop(): failed to access item", exc.index |