Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Python - Tuple Methods

Back


Constructor

tuple(iterable)

print("\n--------- tuple(iterable) --------\n")

# must be iterable
# x_list = tuple(1)  # TypeError: 'int' object is not iterable
# x_list = tuple(1, 2)  # TypeError: set expected at most 1 argument, got 2

# empty set
x_list = tuple()
print(x_list)    # ()

# from tuple
x_list = tuple(('apple', 'banana', 'cherry'))
print(x_list)    # ('apple', 'banana', 'cherry')

# from list
x_list = tuple(['apple', 'banana', 'cherry'])
print(x_list)    # ('apple', 'banana', 'cherry')

# from set
x_list = tuple({'apple', 'banana', 'cherry'})
print(x_list)    # ('cherry', 'apple', 'banana'), order is random

count(value)

print("\n-------- tuple.count(value) --------\n")

x_tuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)

print(x_tuple.count(10))  # 0
print(x_tuple.count(5))  # 2

index(value)

print("\n-------- tuple.count(value) --------\n")

x_list = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)

print(x_list.index(8))  # 3
# print(x_list.index(0)) # ValueError: tuple.index(x): x not in tuple

TOP