Python – Tuple

By | 13/09/2019

A tuple is a collection of immutable objects, separated by commas.
In this post, we will see how to manage Tuples in Python.

CREATE A TUPLE

# empty tuple
tup1 = tuple()
print(f"tuple tup1: {tup1}")

# tuple
tup2 = 1,2
tup3 = 3,"4"
tup4 = ('Damiano', 'Test', 2019)
tup5 = (10,) * 6
print(f"tuple tup2: {tup2}")
print(f"tuple tup3: {tup3}")
print(f"tuple tup4: {tup4}")
print(f"tuple tup5: {tup5}")



CONCATENATION

# Concatenation 
tup6 = tup2 + tup3
print(f"tuple tup2: {tup2}")
print(f"tuple tup3: {tup3}")
print(f"tuple tup6: {tup6}")



NESTING

# Nesting
tup7 = (tup2,tup3)
print(f"tuple tup2: {tup2}")
print(f"tuple tup3: {tup3}")
print(f"tuple tup7: {tup7}")



GET VALUES

# Get values in a tuple
print(f"tuple tup6: {tup6}")
print(f"tuple tup6[0]: {tup6[0]}")
print(f"tuple tup6[3]: {tup6[3]}")
for i in tup6:
    print(i)
print("Second loop")
for i in range(0,len(tup6)):
    print(tup6[i])



DELETE A TUPLE

# Delete tuple
print(f"tuple tup6: {tup6}")
del tup6
print(f"tuple tup6: {tup6}")



UPDATE

# Update tuple
print(f"tuple tup6: {tup6}")
tup6[0] = 5
print(f"tuple tup6: {tup6}")



TUPLE IN ACTION

# define a method to find min and mix in a list
def maxmin(list):
    valMax = max(list)
    valMin = min(list)
    return (valMax,valMin)

# define a list
lst = [1,2,3,4,5,6,7,9,0]
# call the method
findMaxMin = maxmin(lst)

print(f"Max value is:{findMaxMin[0]}")
print(f"Min value is:{findMaxMin[1]}")





Leave a Reply

Your email address will not be published.