CIS 111 Sequences

Objectives

  • Test for membership in a sequence
  • Access elements of a sequence
  • Use slicing to get sections of a sequence

Sequence overview

  • lists, tuples and strings are all sequences
  • have membership tests:
    • in
    • not in
  • support indexing
  • lists, tuples, and strings also support slicing

Sequence examples

17 in [3, 5, 17, 32] # True 17 in [3, 5, 32] # False 17 not in [3, 5, 17, 32] # False 17 not in [3, 5, 32] # True [3, 5, 17, 32][0] # 3 [3, 5, 17, 32][2] # 17 a = [3, 5, 17, 32] a[0] # 3 a[2] # 17 a[-1] # 32 (last item) a[-2] # 17 (next to last item) a = [3, 5, 17, 32, 2, 15] a[1:4] # [5, 17, 32] a[1:-1] # [5, 17, 32, 2] a[:] # [3, 5, 17, 32, 2, 15] a[1:] # [5, 17, 32, 2, 15] (start at 1) a[::2] # [3, 17, 2] (every 2nd item starting at 0) a[1::3] # [5, 2] (every 3rd item starting at 1) a[::-1] # [15, 2, 32, 17, 5, 3] (reverse order)