Today I Learned

A Hashrocket project

Python has tuples!

I love a good tuple and in JavaScript or Ruby I sometimes use arrays as tuples.

[thing, 1, "Description"]

In those languages however, this tuple isn’t finite. Wikipedia defines tuple thusly.

a tuple is a finite ordered list (sequence) of elements.

Python tuples look like this:

mytuple = (thing, 1, "Description")

And is it finite?

>>> mytuple.append("c")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'

No append attribute, ok. But can you add tuples together?

>>> a = ('a', 'b')
>>> a + ('c', 'd')
('a', 'b', 'c', 'd')
>>> a
('a', 'b')

You can add tuples together but it’s not mutative.

A syntax quirk is the one element tuple.

>>> type(('c'))
<class 'str'>
>>> type(('c',))
<class 'tuple'>

Include a comma after the only tuple element to ensure that the tuple is not tokenized as a string.