A tuple is an immutable list of Python objects which means it can not be changed in any way once it has been created. Unlike sets, tuples are an ordered collection.
Now let’s take a look at an example of a tuple.
tupleExmp = ("alpha","bravo","charlie")print(tupleExmp)
Once a tuple is created, items cannot be added or removed and their values cannot be changed. Changing the above tuple will generate an error.
tupleExmp = ("alpha","bravo","charlie")tupleExmp[0] = "100" #changing the value at zeroth index
Tuple indexes are zero-based, just like a list, so the first element of a non-empty tuple is always tuple[0]
.
Negative indexes count from the end of the tuple, just like a list.
tupleExmp = ("alpha","bravo","charlie")print(tupleExmp[1])print(tupleExmp[-1])
You can also loop through the tuple values using a for
loop.
tupleExmp = ("alpha","bravo","charlie")for item in tupleExmp:print(item)
The length of a tuple can be found using the len()
function.
tupleExmp = ("alpha","bravo","charlie")print(len(tupleExmp))
Free Resources