LearnWave
Learn it. Master it.

Tuples and Dictionaries

Tuple operations

Extend a tuple by making a new one.

Operations on tuples, each of which makes a new tuple (the original never changes):

  • Concatenation with +: (5, 6) + (7,) gives (5, 6, 7). Both sides must be tuples. To 'extend' a tuple, make a new one: t = t + (8,) (note the comma, which makes (8,) a tuple).
  • Repetition with *: ('Go',) * 2 gives ('Go', 'Go'). The first operand is a tuple, the second an integer.
  • Membership with in and not in: 'Green' in ('Red', 'Green', 'Blue') is True.

Slicing works just as for lists. For t = (2, 4, 6, 8, 10, 12):

  • t[1:4] is (4, 6, 8).
  • t[:2] is (2, 4), and t[3:] is (8, 10, 12).
  • t[0:len(t):2] is (2, 6, 10): every second element.
  • t[-2:] is (10, 12).
  • t[::-1] is the tuple reversed: (12, 10, 8, 6, 4, 2).
New tuple every time.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.