The(20, 10) is a tuple. A tuple is a data structure in Python that is quite similar to a list but with some key differences. One common way to encounter a tuple is when a function returns multiple values.
For instance, consider this function that returns both the sum and the difference of two numbers:
def sum_and_difference (a, b):
a_sum = a + b
difference = a - b
return a_sum, difference
# We switched the order of return values
sum_diff = sum_and_difference(15, 5)
print(type(sum_diff))
Output
<class 'tuple'>
The function type() confirms that what's returned is a tuple.
Just like a list, we usually use a tuple to store multiple values. To create a tuple, we use parentheses to enclose the elements, separated by commas. Here's how we create and verify the type of a tuple:
a_tuple = (1, 'a', 10.5)
a_tuple[0] = 99 # This will result in an error
print(a_tuple)
Output
TypeError: 'tuple' object does not support item assignment
def sum_and_difference (a, b):
a_sum = a + b
difference = a - b
return [a_sum, difference]
# Use brackets to return a list
sum_diff = sum_and_difference(15, 5)
print(sum_diff)
print(type(sum_diff))
Output
[20, 10]
<class 'list'>
def sum_and_difference(a, b, do_sum=True):
a_sum = a + b
difference = a - b
return a_sum, difference
a_sum, a_diff = sum_and_difference(15, 5)
print(a_sum)
print(a_diff)
Output
20
10
def display_table(dataset, index):
table = freq_table(dataset, index)
table_display = []
for key in table:
key_val_as_tuple = (table[key], key)
table_display.append(key_val_as_tuple)
table_sorted = sorted(table_display, reverse = True)
for entry in table_sorted:
print(entry[1], ':', entry[0])