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')
x = tuple(('one','two','three'))
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

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')

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.

Written by

Hi

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store