Friday, July 1, 2022

Python - Tuples

# Lists use a square bracket []
# Tuples use parentheses ()
mylist =  ["apple", "banana", "cherry", "apple"]
mytuple = ("apple", "banana", "cherry", "apple")

#<class 'list'>
#<class 'tuple'>
print (type(mylist))
print (type(mytuple))

# Length of tuple
# 4
print(len(mytuple))

# A tuple with only one item is a bit gnarly
# Notice the ending comma:
thistuple = ("apple",)
# If we forget the comma it is a string
myString = ("apple")

# <class 'str'>
print (type(myString))

# Since tuples are "unchangeable", we must jump thru some hoops
# if we *do* want to change one.
# Set up a tuple
x = ("apple", "banana", "cherry")
# Create a list type of the tuple
y = list(x)
# Make your change
y[1] = "kiwi"
# Now redefine the original tuple as a tuple
#   but give it the contents of the changed list
x = tuple(y)

print(x)

# Adding items to an unchangeable tuple is similar
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
print(thistuple)

print("---")

# Removing an item from an unchangeable tuple is similar
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
print(thistuple)