Python Tuples
Overview
Tuples are similar to lists where they are ordered, but unlike lists tuples are immutable. When you try to change a value in a tuple it will throw a type error. Similarly you cannot add or remove values either.
Creating
To create a tuple you use parenthesis instead of square brackets and just provide it the values separated by commas.
x = ('one','two','three')
Another way is to use the tuple constructor but be aware of the extra parenthesis.
x = tuple(('one','two','three'))
You can create a tuple with one value but you need to add a comma.
x = ('one',)
print(x)
>> ('one',)notTuple = ('one')
print(notTuple)
>> 'one'
Read Value
Like lists you can access values by using the index of the tuple.
x = ('one','two','three')
print(x[1])
>> two
Similarly lists you can use negative values and range of index as well.
Updating Values
While it is true you cannot change the values in a tuple there is a work around. By converting the tuple into a list you, change the value and then converting it back into a tuple.
x = ("one", "two", "three")
tupleList = list(x)
tupleList[1] = "four"
x = tuple(tupleList)print(x)
>> ('one', 'four', 'three')
It is possible to add and remove values this way as well.
Delete Tuple
To delete the entire tuple you can use the del keyword.
x = ('one', 'two', 'three')
del x
print(x) # Will throw error because tuple doe snot exist anymore
Joining Tuples
To combine tuples you can use to + operator.
tuple1 = ('one', 'two', 'three')
tuple2 = ('four', 'five', 'six')
tuple3 = tuple1 + tuple2
print(tuple3)
>> ('one', 'two', 'three', 'four', 'five', 'six')
Conclusion
Tuples can be considered lists that are immutable. You might want to use tuples over lists if you want to return multiple results from a function or you want to use keys in a dictionary.