Tuples
Tuples and lists can be converted one to the other by invoking their Constructors.
A single item tuple needs a trailing comma to properly set its type. But since you cannot change or add to it, what is the purpose? Actually there are workarounds. First you could fully delete the tuple from memory and start again. Second, you can convert it to a list, make additions or removals and changes, then convert it back to a tuple. Third you can join one tuple "as-is" to another tuple, which is essentially a type of rough add command.
sports = ("baseball", "football", "basketball")
one_sport = ("baseball",) # a tuple
another_sport = ("football") # a string variable
print(type(one_sport)) # <class: 'tuple'>
print(type(another_sport)) # <class: 'str'>
print(type(sports)) # <class: 'tuple'>
sports = ("baseball", "football", "basketball")
del sports
sports = tuple(("football", "tennis")) # use constructor to create a tuple on the flyoption 2 to change a tuple
sports = ("baseball", "football", "basketball")
sports = list(sports)
sports.insert(0, "hockey")
sports = tuple(sports)
print(sports)
print(type(sports))
# results in 'hockey', 'baseball', 'football', 'basketball'
# <class: 'tuple'>
option 3 to change a tuple
more_sports = ("handball", "bowling")
all_sports = sports + more_sports
# a larger tuple but the additional elements are still
# inserted randomly.
The tuple data type only has two methods: count() and index(), each of which needs only one argument. index() will return the position of the found value in the tuple; if there are multiple matches to the value (duplicates) it will only return the leftmost match.
Compared to the other 3 collection type variables, a tuple is the most restricted in what can be done to it.
No comments:
Post a Comment