Lesson 44 +10 XP

Loop and Join Tuples

Looping over a tuple works just like a list; joining makes a new tuple.

Loop with for


python
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
    print(x)

Loop by index


python
for i in range(len(thistuple)):
    print(thistuple[i])

While loop


python
i = 0
while i < len(thistuple):
    print(thistuple[i])
    i += 1

Join two tuples with +


python
tuple1 = ("a", "b")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)

### ('a', 'b', 1, 2, 3)

Multiply a tuple


python
tuple4 = tuple1 * 2
print(tuple4)

### ('a', 'b', 'a', 'b')

Count and index methods

Tuples have only two methods:


python
t = (1, 2, 2, 3)
print(t.count(2))

### 2
print(t.index(3))

### 3

TL;DR

  • Loop with for, range, or while.
  • + joins tuples into a new one.
  • * repeats a tuple.
  • Only count() and index() are built in.