Skip to main content

PYTHON TUPLES

T
UPLES
thistuple = ("apple",20, "cherry",True,False,3)
Note the double round-brackets
print(thistuple)
('apple', 20, 'cherry', True, False, 3)
print(type(thistuple))
<class 'tuple'>
thistuple = tuple(("apple",20, "cherry",True,False,3.0))
print(thistuple)
('apple', 20, 'cherry', True, False, 3.0)
print(type(thistuple))
<class 'tuple'>
Access Tuples
print(thistuple[1])
20
print(thistuple[-4])
cherry
print(thistuple[-4:])
('cherry', True, False, 3.0)
print(thistuple[1:])
(20, 'cherry', True, False, 3.0)
Add and Remove Tuples Values
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
('apple', 'kiwi', 'cherry')
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
print(thistuple)
('apple', 'banana', 'cherry', 'orange')
y = ("orange",)
thistuple += y
print(thistuple)
('apple', 'banana', 'cherry', 'orange')
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
Unpack Tuples

fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruits
print(type(green),green)
<class 'str'> apple
print(type(tropic),tropic)
<class 'list'> ['mango', 'papaya', 'pineapple']
print(red)
cherry
Loop Tuples
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
  print(thistuple[i])
apple
banana
cherry
Join Tuples
tuple2 = (1, 2, 3)
mytuple = tuple2 + fruits
print(mytuple)
(1, 2, 3, 'apple', 'mango', 'papaya', 'pineapple', 'cherry')
mytuple = fruits * 2
print(mytuple)
('apple', 'mango', 'papaya', 'pineapple', 'cherry', 'apple', 'mango', 'papaya', 'pineapple', 'cherry')

Comments