SimpleTuts.com

Python Tuples

Python tuples are immutable sequences of elements, typically used to store heterogeneous data where each element can be accessed via indexing.


#Python Tuples
#Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

mytuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")

#list length
print("Length : ",len(mytuple))

#Get items
print("All values : ",mytuple)
print("Single Item : ",mytuple[1])
print("Negetive indexing : ",mytuple[-1])
print("Range of values : ",mytuple[2:5])
print("Range from beginning : ",mytuple[:4])
print("Range to end : ",mytuple[2:])
print("Negative range : ",mytuple[-4:-1])

# change items
mylist = list(mytuple)
mylist[1] = "blackcurrant"
mytuple = tuple(mylist)
print("After change : ",mytuple)

#add items
mylist = list(mytuple)
mylist.append("blueberry")
mytuple = tuple(mylist)
print("After add : ",mytuple)

#Remove items
mylist = list(mytuple)
mylist.remove("apple")
mytuple = tuple(mylist)
print("After remove : ",mytuple)


#Unpacking
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print("Unpacked values : ")
print(green)
print(yellow)
print(red)

#check item
print("Checking an item in tuple:")
if "melon" in mytuple:
  print("Yes, 'melon' is in the tuple")

#Loop tuple
print("Print items using loop:")
for x in mytuple:
  print(x)
                
Python Online Compiler