Loading lessons...
Loop and Join Tuples
Loop and Join Tuples
Looping over a tuple works just like a list; joining makes a new tuple.
Loop with for
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
Loop by index
for i in range(len(thistuple)):
print(thistuple[i])
While loop
i = 0
while i < len(thistuple):
print(thistuple[i])
i += 1
Join two tuples with +
tuple1 = ("a", "b")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3) # ('a', 'b', 1, 2, 3)
Multiply a tuple
tuple4 = tuple1 * 2
print(tuple4) # ('a', 'b', 'a', 'b')
Count and index methods
Tuples have only two methods:
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.