Next Video: How to use conditionals and loops in Python
are another type of data sequences, but differently to lists, they are immutable. Tuples cannot be changed or modified; you cannot append or delete elements. The syntax that indicates you are having a tuple and not a list is that the tuple’s elements are placed within parentheses and not brackets.
By the way, the tuple is the default sequence type in Python, so if I enlist three values here, the computer will perceive the new variable as a tuple. We could also say the three values will be packed into a tuple.
For the same reason, we can assign a number of values to the same number of variables. Do you remember we went through that a few lectures ago? On the left side of the equality sign, we just added a tuple of variables, and on the right, a tuple of values. That’s why the relevant technical term for this activity is tuple assignment.
In the same way we can do for lists, we can index values by indicating their position in brackets.
In addition, we can also place Python tuples within lists. And then, each tuple becomes a separate element within the list.
Python tuples are similar to lists, but there are some subtle differences we should not overlook.
They can be quite useful when dealing with different comma-separated values. For example, if we have age and years of school as variables, and I have the respective numbers in a string format, separated by a comma (hence the name comma-separated values), the split method with the proper indication within the parentheses will assign 30 as a value for age and 17 as a value for years of school. We can print the two variables separately to check the outcome…
Everything seems to be correct – awesome!
Last, functions can provide tuples as return values. This is useful because a function (which can only return a single value otherwise), can produce a tuple holding multiple values. Check this code; I will input only the length of the side of a square, and as an output, the “square info” function will return a tuple. The tuple will tell me the area and the perimeter of the square.
This is how we can work with tuples in Python! Thanks for watching!
Curious to learn more? Check out our Python for Finance: Investment Fundamentals and Data Analytics course here.