Another aspect that connects strings and tuples is that they are both immutable. Just like you can't replace a character in a string, you also can't replace an element in a tuple.
You can, however, create a new tuple from an old tuple:
tup = (1, 42, "hello!")
tup2 = tup[:2]
print(tup2) # OUTPUT: (1, 42)
Combining Tuples
Just like with strings, you can also use the + operator to add two tuples together and create a new tuple with the combined elements:
tup = (1, 42)
tup2 = (123, 999)
tup3 = tup + tup2
print(tup3) # OUTPUT: (1, 42, 123, 999)
As you can see, the new tuple tup3 contains all elements of tup and tup2 stuck together just like you'd expect it with a string.
Keep in mind that neither tup nor tup2 has changed at all. They are immutable and can't change, but you can use them to create new tuple elements. Like with strings, you can also overwrite the variable reference to an existing tuple with a new tuple object:
tup = (1, 42)
tup2 = (123, 999)
tup = tup + tup2
print(tup) # OUTPUT: (1, 42, 123, 999)
Here, you did the same thing as in the code snippet above, but instead of assigning the output of the tuple concatenation to a new variable, tup3, you overwrote the existing variable tup with a new tuple object value.
Info: The tuple object that tup originally referred to never changed. Instead, you discarded the reference to it and assigned the variable name tup to a different tuple object. Python automatically finds and deletes abandoned objects that no longer have any reference to them.
You can train your understanding of this new data type by mobilizing your knowledge about strings. Both data types behave similarly. However, you'll soon notice that they have different use cases since tuples can be used as containers for other data structures.
Tuple Practice
- Create a
forloop and iterate over one of your tuples. Print out each element. - Create a tuple that is a collection of only
strelements. Access the second letter of the second element in your tuple using indexing. - Iterate over your tuple full of strings and print out the last letter of each string only. For this, you'll need to combine iteration and indexing.
# your turn!
Additional Resources
- Python Documentation: Tuples and sequences
Summary: How to Define Immutable Tuples
- Tuples are another immutable sequence data type in Python that behaves similarly to strings. You can't change a tuple, but you can create a new tuple object with changed content.
- Unlike strings, tuples can also contain any other data type as an element, which makes them very versatile and useful.
- In the next lesson, you'll meet another sequence data type in Python called list, which is similar to tuples in that it can contain any other data type but is different because you can change the elements in a list.