Tuples

In Python, tuples are almost identical to lists. So, why should we use them you ask? The one main difference between tuples and lists are that tuples cannot be changed. That is to say you cannot add, change, or delete elements from the tuple. Tuples might seem odd at first, but there is a great reason behind them being immutable. As programmers, we mess up occasionally. We change variables that we didn’t want to change, and sometimes, well, we just want things to be constant so we don’t accidentally change them later. However, if we change our minds we can also convert tuples into lists or lists into tuples. The fact is we need to make the conscious effort to say Python, I want to change this tuple into a list so I can modify it. Enough babbling, let’s see a tuple in action!

List vs. Tuple

Example
myList = [1,2,3]
myList.append(4)
print (myList)

myTuple = (1,2,3)
print (myTuple)

myTuple2 = (1,2,3)
myTuple2.append(4)
print (myTuple2)
Result [1, 2, 3, 4]
(1, 2, 3)
Traceback (most recent call last):
File “C:/Python32/test”, line 9, in
myTuple2.append(4)
AttributeError: ‘tuple’ object has no attribute ‘append’

So, we see that the list clearly works as expected. We just append a 4 onto the end, and Python doesn’t miss a beat. Next, we test out our tuple declaration and it works as well. But when we try to append to the tuple, Python give us a nasty little error. Like I said, you cannot change a tuple! Python will bite you if you try using things like append on a tuple. But, let’s say “Hey, I really want to add a four to that tuple.” Let’s do it:

Example
myTuple = (1,2,3)
myList = list(myTuple)
myList.append(4)
print (myList)
Result [1, 2, 3, 4]

Boom! We have successfully undone what Python was trying to teach us not to do. We just casted the tuple into a list, then once it was a list, we used it’s append method to add the 4. It should be reiterated that the purpose of a tuple is to be immutable. If you are planning to change the variable, just use a list instead.