# Tuple Basics

- Apr 1 • 6 min read
- Key Terms: tuples

A tuple is a sequence of values. The values can be of any type.

A major difference between tuples and other data structures is that tuples are immutable. Because tuples are immutable, you can't modify elements inside of a tuple.

This immutability could be helpful if you're writing a program and want to store data that shouldn't be changed. Possible examples include:

- credit card information
- birthdate
- birth name

#### How to create a tuple

Tuples are comma-separated values. It is common to enclose tuples in parentheses.

```
data = (1, 2)
```

To create a tuple with a single element, you have to include a final comma.

```
more_data = (3,)
```

We can verify this data structure is a tuple by passing it into the `type()`

function.

```
type(more_data)
```

```
tuple
```

#### Retrieve a tuple element via indexing

Similar to lists, tuples can be indexed by integers using the bracket operator.

```
values = (1, 2, 3)
```

We can retrieve the number `3`

in our `values`

tuple at index position of `2`

.

```
values[2]
```

```
3
```

#### Tuple assignment

In Python, you can call the `split()`

method on a string and pass in an argument to split the string on.

We can split the string below, my email address, in half on the `@`

symbol since there is just one in the string.

This operation returns a list.

```
'dan@dfrieds.com'.split('@')
```

```
['dan', 'dfrieds.com']
```

We can also assign `username`

and `domain`

, comma-separated tuple elements, to be the result of the two elements after the split operation.

In doing this, the number of variables on the left and the number of variables on the right side of our expression have to be the same. In this case, it's 2.

```
username, domain = 'dan@dfrieds.com'.split('@')
```

```
username
```

```
'dan'
```

```
domain
```

```
'dfrieds.com'
```

The right side of this assignment returned a list. However, in Python, for tuple assignments, it could work with any kind of sequence such as a string, list or tuple.

#### Tuples as return values of functions

A function can only return one value. However, that one value could be a tuple - similar to the effect of returning multiple values.

For example, we can use a built-in Python function called `divmod`

to compute the quotient and remainder at the same time.

```
9/2 = 4.5
```

However, you can also express that result as a quotient of 4 with a remainder of 1.

```
divmod(9, 2)
```

```
(4, 1)
```

We can store this result as a tuple.

```
tuple_result = divmod(9, 2)
```

```
tuple_result
```

```
(4, 1)
```

Or we can use tuple assignment to store the elements separately as variables.

```
quotient, remainder = divmod(9, 2)
```

```
quotient
```

```
4
```

```
remainder
```

```
1
```

We can also write our own function that returns a tuple of two elements.

```
def calculate_quotient_and_remainder(dividend, divisor):
"""
Given two numbers, calculate the quotient and remainder
:param dividend: a number meant to be the numerator of our equation
:param divisor: a number meant to be the denominator of our equation
:returns: quotient, remainder: a tuple of our (quotient, remainder)
"""
quotient = dividend // divisor
remainder = dividend % divisor
return quotient, remainder
```

```
calculate_quotient_and_remainder(9, 2)
```

```
(4, 1)
```

#### Tuples and dictionaries

`items`

method for dictionaries

Tuples can be useful as dictionary keys too since they can hold multiple values.

You cannot use a Python list for a dictionary key.

Let's say you had a record of friends and their phone numbers in a program stored as a dictionary.

```
friends = {"Eric Friedman": 5555555555, "Dan Friedman": 5551231234}
```

Dictionaries have a method called `items`

that returns a sequence of tuples, where each tuple is a key-value pair.

```
friends.items()
```

```
dict_items([('Eric Friedman', 5555555555), ('Dan Friedman', 5551231234)])
```

This result is a `dict_items`

object, which is an iterator that iterates the key-value pairs.

##### Sort dictionary keys

A common operation you may want to do with a record of contact names and phone numbers is to sort names by either first name or last name.

We can use the Python built-in `sorted`

method to sort our keys alphabetically. Because of our string names, this will default to sort by first names alphabetically.

```
sorted(friends.items())
```

```
[('Dan Friedman', 5551231234), ('Eric Friedman', 5555555555)]
```

Notice how `Dan`

appears now before `Eric`

and we're returned a new list of tuples.

However, what if we want to sort by last name?

There may be a complex way to do it given our current data structure. However, we could simply represent the keys of our dictionary as (first_name, last_name) - a tuple. This may help us more easily sort by first or last name later on.

```
new_friends = {("Dan", "Williams"): 5555555555, ("Jamie", "Brown"): 5551231234}
```

This code below sorts the friends last names alphabetically from A to Z.

We pass a value to the second argument of `sorted`

that's a small anonymous function; this function uses the `lambda`

keyword so we sort by the value at index `1`

in each dictionary key - in which index `1`

is the last name of each tuple.

```
sorted(new_friends.items(), key=lambda x: x[1])
```

```
[(('Jamie', 'Brown'), 5551231234), (('Dan', 'Williams'), 5555555555)]
```

Notice how `Brown`

appears before `Williams`

since *b* comes before *w* in the alphabet.

This is just one example of how storing dictionary keys as tuples could be valuable for later data manipulation.