Structuring data in Python (Part 2)

Immutable sequences in Python

Another item on our wish list was immutable sequences. Python has what are called tuples. Tuples in Python are immutable sequences.

How tuples are entered:
Parentheses around the tuple,
items separated by commas.
E.g., (6, 2, 4, 3).
How tuples are displayed:
Parentheses around the tuple,
items separated by commas.
E.g., (6, 2, 4, 3).

We've already seen how strings and lists behave similarly and how many of the same functions work for both. Tuples work in the same way. Tuples are entered and displayed using parentheses to demarcate the tuple and commas to separate elements.

Caution

Put a comma after the only element in a tuple of length 1.
An empty tuple has no commas.

Be careful of the one quirk that differentiates these from how lists look: if a tuple has a single value, it still needs to be followed by a comma.


Tuples

Here's a reminder that if you write a single value without a comma, it is not interpreted as a tuple. Running the code

print(())
print((1, 2))
print((1))
print((1,))

gives the output

()
(1, 2)
1
(1,)

So watch out for that in the future.

Here are a few tuples we can use as inputs to some built-in functions. I don't think there will be any surprises here.

first_tup = (1, 2, 3)
second_tup = ("a", "b", "c")

We define the tuples.


print(len(first_tup))

We can figure out the length.


print(first_tup[-1])

We extract an item.


print(first_tup + second_tup)

We concatenate two tuples.


print(2 * second_tup)

We can use an asterisk for repeated concatenation.


print(first_tup[1:2])

We can use slices to extract smaller tuples.


print((1, 2) < (2, 3))

We can use comparisons to compare tuples item by item.


Here's the complete sequence of statements and their output:

first_tup = (1, 2, 3)
second_tup = ("a", "b", "c")

print(len(first_tup))
print(first_tup[-1])
print(first_tup + second_tup)

print(2 * second_tup)
print(first_tup[1:2])
print((1, 2) < (2, 3))
3
3
(1, 2, 3, 'a', 'b', 'c')
('a', 'b', 'c', 'a', 'b', 'c')
(2,)
True

Here is a summary of the operations we used:

FunctionPythonValue
tuple lengthlen((1, 2, 3))3
index(1, 2, 3)[0]1
concatenation(1, 2) + (3,)(1, 2, 3)
repeated2 * (1, 2, 3)(1, 2, 3, 1, 2, 3)
slice(1, 2, 3)[1:2](2,)
comparison(1, 2) < (2, 3)True

Just like for lists, for concatenation we need to make sure that we concatenate two tuples, not a tuple and an element. Just like for lists, comparisons only work when correponding items are comparable.


The function tuple

Just like there is a function list that creates lists from sequences, there is function tuple that creates tuples from sequences.

print(tuple())

We create an empty tuple, giving the output () when the code is run.


Running the code

print(tuple(1, 2))

gives the error

Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: tuple() takes at most 1 argument (2 given)

The error is generated since the input needs to be a sequence.

print(tuple((1, 2)))

We use a tuple as the input, giving the output (1, 2).


print(tuple([1, 2]))

We use a list as the input, giving the output (1, 2).


print(tuple("12"))

We use a string as the input, giving the output ('1', '2').


Notice that we obtain a tuple of the items in the sequence, no matter what type it is.

Here's a summary of how the function can be used to create a new tuple from some sequences:

  • tuple()
  • tuple("string")
  • tuple([1, 2, 3])
  • tuple((1, 2, 3))

Caution

The input must be a sequence.


More tuple functions

You'll see many familar functions here.

min and max produce the minimum and maximum values in the tuple, provided that there is an ordering on the elements. That is, these functions will work if all elements are numbers or all elements are strings, but not for a mixture of numbers and strings. For example, running the code

tup = (3, 6, 7, 4, 1, 4, 2, 5)
print(min(tup))
print(max(tup))

gives the output

1
7

The function count determines how many times an item is in the tuple, and the function index determines the position of the first occurrence of an item. For example, the code

tup = (3, 6, 7, 4, 1, 4, 2, 5)
print(tup.count(4))
print(tup.index(7))

gives the output

2
2

Just like for other sequences, we can use in to determine if an element is in a tuple. Then, there are the functions that produce a list, namely list and sorted. For example, running the code

tup = (3, 6, 7, 4, 1, 4, 2, 5)
print(2 in tup)
print(list(tup))
print(sorted(tup))

gives the output

True
[3, 6, 7, 4, 1, 4, 2, 5]
[1, 2, 3, 4, 4, 5, 6, 7]

Here is the summary, which should look very familiar as well, as these were also functions we used on lists and strings:

Common sequence functions (also for lists and strings)
FunctionPython
minimummin(tup)
maximummax(tup)
counttup.count(4)
searchtup.index(7)
membership2 in tup
new listlist(tup)
sortsorted(tup)