Facebook   Tumblr   LinkedIn

Python Tuples

Walden Systems Geeks Corner Tutorial Python Tuples Rutherford NJ New Jersey NYC New York City North Bergen County
Python is a programming language that lets you work quickly and integrate systems more effectively.

In Python, a tuple is a comma-separated sequence of values. Very similar to a list. However, there's an important difference between the two. The main difference between tuples and lists is that lists are mutable and tuples are not. A mutable object is one that can be changed. An immutable object is one that contains a fixed value that cannot be changed. If it needs to be changed, a new object must be created. Generally, we store different data inside a tuple than we would a list. Lists usually contain items that are similar to each other, whereas tuples usually contain items that are different in type or character. There's no rule to this. If we want to be able to update the individual items, we use a list. Otherwise, we use a tuple.

We can tuple just like we create a list, except that we use regular brackets instead of square brackets. If we create a tuple with a single item, we need to include a comma at the end, otherwise we'll end up with a string. Tuples can hold different data types including lists so we can have a tuple with an element being a list. We access the values in a tuple by using the variable name with an index value enclosed in square brackets. We can also pick a range of values by using two indices separated by a colon. This returns all items up to, but not including the second index specified. Keep in mind that when accessing values, the index starts at zero.

As mentioned earlier, tuples can't be changed which means that we can't change any values in the tuple. In order to change a tuple, we have to reassign a tuple by assigning the tuple a comply new set of values. Although you can't change tuple items, you can change list items within a tuple, since the list is a value in the tuple and the list can be changed. We can concatenate, or join a tuple with another one to create a new a tuple that contains values from both tuples. We can't delete individual tuple items but we can use the del keyword to delete the whole tuple.

Instead of accessing values in a tuple by index, we can access it by name by using Named Tuples. A named tuple allows us to reference each item by a name, rather than its index. This can help the readability of our code since it's much easier to see which values are being referenced in a block of code.

We can conclude that although both lists and tuples are data structures in Python, there are remarkable differences between the two, with the main difference being that lists are mutable while tuples are immutable. A list has a variable size while a tuple has a fixed size. Operations on tuples can be executed faster compared to operations on lists.