# Python Programming/Tuples and Sets

This lesson introduces Python tuples and sets by comparing them to lists and dictionaries.

## Objectives and Skills

Objectives and skills for this lesson include:[1]

• Data Structures
• Tuple
• Sequences
• Set

## Multimedia

1. YouTube: Python for Informatics - Chapter 10 - Tuples

## Examples

### Data Structures

Python data structures include lists, dictionaries, tuples, and sets.[2]

```list = [1, 2, 3]
dictionary = {1: "one", 2: "two", 3: "three"}
tuple = (1, 2, 3)
set = {1, 2, 3}

print("list:", list)
print("dictionary:", dictionary)
print("tuple:", tuple)
print("set:", set)
```

Output:

```list: [1, 2, 3]
dictionary: {1: 'one', 2: 'two', 3: 'three'}
tuple: (1, 2, 3)
set: {1, 2, 3}
```

### Data Types

The data types for a list, dictionary, tuple, and set, are 'list', 'dict', 'tuple', and 'set', respectively.[3]

```list = [1, 2, 3]
dictionary = {1: "one", 2: "two", 3: "three"}
tuple = (1, 2, 3)
set = {1, 2, 3}

print("list:", type(list))
print("dictionary:", type(dictionary))
print("tuple:", type(tuple))
print("set:", type(set))
```

Output:

```list: <class 'list'>
dictionary: <class 'dict'>
tuple: <class 'tuple'>
set: <class 'set'>
```

### Functions

The list(), dict(), tuple(), and set() functions may be used to create list, dictionary, tuple, and set objects, respectively.[4]

```print(list((1, 2, 3)))
print(dict(one = 1, two = 2, three = 3))
print(tuple((1, 2, 3)))
print(set((1, 2, 3)))
```

Output:

```[1, 2, 3]
{'three': 3, 'two': 2, 'one': 1}
(1, 2, 3)
{1, 2, 3}
```

### Mutability

List, dictionary and set items are mutable. Tuple items are immutable.[5]

```list = [1, 2, 3]
dictionary = {1: "one", 2: "two", 3: "three"}
tuple = (1, 2, 3)
set = {1, 2, 3}

list[0] = 0
print("list: mutable")

dictionary[1] = "zero"
print("dictionary: mutable")

try:
tuple[0] = 0
print("tuple: mutable")
except:
print("tuple: immutable")

try:
set |= {0}
print("set: mutable")
except:
print("set: immutable")

print()
print("list:", list)
print("dictionary:", dictionary)
print("tuple:", tuple)
print("set:", set)
```

Output:

```list: mutable
dictionary: mutable
tuple: immutable
set: mutable

list: [0, 2, 3]
dictionary: {1: 'zero', 2: 'two', 3: 'three'}
tuple: (1, 2, 3)
set: {0, 1, 2, 3}
```

### Order

Lists and tuples maintain order. Dictionaries and sets are unordered.[6]

```list = ["fish", "dog", "cat"]
tuple = ("fish", "dog", "cat")
dictionary = {
'fish': 'Bubbles',
'dog': 'Spot',
'cat': 'Frisky',
}
set = {"fish", "dog", "cat"}

print("list:", list)
print("dictionary:", dictionary)
print("tuple:", tuple)
print("set:", set)
```

Output:

```list: ['fish', 'dog', 'cat']
tuple: ('fish', 'dog', 'cat')
dictionary: {'dog': 'Spot', 'fish': 'Bubbles', 'cat': 'Frisky'}
set: {'dog', 'fish', 'cat'}
```

### Duplication

Lists and tuples allow duplication. Dictionary and set items are unique.[7]

```list = [1, 1, 1]
tuple = (1, 1, 1)
dictionary = {1: 'one', 1: 'one', 1: 'one'}
set = {1, 1, 1}

print("list:", list)
print("tuple:", tuple)
print("dictionary:", dictionary)
print("set:", set)
```

Output:

```list: [1, 1, 1]
tuple: (1, 1, 1)
dictionary: {1: 'one'}
set: {1}
```

Sets may be used to remove duplication found in other data structures.[8]

```list = [1, 1, 1]
tuple = (1, 1, 1)

print("list:", list)
print("set:", set(list))

print("tuple:", tuple)
print("set:", set(tuple))
```

Output:

```list: [1, 1, 1]
set: {1}
tuple: (1, 1, 1)
set: {1}
```

### Looping

List, dictionary, tuple, and set items may be accessed using a for loop.[9]

```list = ["fish", "dog", "cat"]
tuple = ("fish", "dog", "cat")
dictionary = {
'fish': 'Bubbles',
'dog': 'Spot',
'cat': 'Frisky',
}
set = {"fish", "dog", "cat"}

print("List:")
for item in list:
print(item)
print()

print("Dictionary:")
for item in dictionary:
print(item)
print()

print("Tuple:")
for item in tuple:
print(item)
print()

print("Set:")
for item in set:
print(item)
```

Output:

```List:
fish
dog
cat

Dictionary:
cat
fish
dog

Tuple:
fish
dog
cat

Set:
cat
fish
dog```

### Index

List and tuple items may be accessed by index. Dictionary items are accessed by key. Set items cannot be accessed by index.[10]

```list = [1, 2, 3]
dictionary = {1: "one", 2: "two", 3: "three"}
tuple = (1, 2, 3)
set = {1, 2, 3}

for i in range(len(list)):
print("list[%d]: %d" % (i, list[i]))
print()

for key in dictionary:
print("dictionary[%s]: %s" % (key, dictionary[key]))
print()

for i in range(len(tuple)):
print("tuple[%d]: %d" % (i, tuple[i]))
print()

try:
for i in range(len(set)):
print("set[%d]: %d" % (i, set[i]))
except Exception as exception:
print(exception)
```

Output:

```list[0]: 1
list[1]: 2
list[2]: 3

dictionary[1]: one
dictionary[2]: two
dictionary[3]: three

tuple[0]: 1
tuple[1]: 2
tuple[2]: 3

'set' object does not support indexing
```

### Tuple Assignment

Python supports having a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time.[11]

```x = 1
y = 2
print(x, y)

x, y = y, x
print(x, y)
```

Output:

```1 2
2 1
```

### Set Operations

Sets support logical set operations, including membership, subset, superset, union (|), intersection (&), and difference (-).[12]

```numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
even = {2, 4, 6, 8, 10}
odd = {1, 3, 5, 7, 9}

print("Numbers:", numbers)
print("Even:", even)
print("Odd:", odd)

print("1 in numbers:", 1 in numbers)
print("even.issubset(numbers):", even.issubset(numbers))
print("numbers.issuperset(odd):", numbers.issuperset(odd))
print("even | odd:", even | odd)
print("even & odd:", even & odd)
print("numbers - even:", numbers - even)
```

Output:

```Numbers: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Even: {8, 10, 2, 4, 6}
Odd: {9, 1, 3, 5, 7}
1 in numbers: True
even.issubset(numbers): True
numbers.issuperset(odd): True
even | odd: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
even & odd: set()
numbers - even: {1, 9, 3, 5, 7}
```

## Activities

### Tutorials

1. Complete one or more of the following tutorials:

### Practice

1. Create a Python program that contains a dictionary of names and phone numbers. Use a tuple of separate first and last name values for the key field. Initialize the dictionary with at least three names and numbers. Ask the user to search for a phone number by entering a first and last name. Display the matching number if found, or a message if not found.
2. Create a Python program that contains a dictionary of names and phone numbers. Use a tuple of separate first and last name values for the key field. Allow the user to enter names and numbers and add them to the dictionary. When the user is finished adding entries, display the names and numbers sorted in alphabetical order by last name and first name.
3. Create a Python program that asks the user to enter a line of text. Use the string split() method to parse the line and then display the list of words in alphabetical order with any duplicate words removed from the list. Use set() to remove the duplicates.
4. Create a Python program that asks the user to enter two sets of comma-separated values. Use the string split() method to parse the line and then use the set() function to covert the lists to sets. Demonstrate set theory for the two sets by displaying the two sets and their relationship to each other as subset, superset, union, intersection, and difference.

## Lesson Summary

### Data Structure Concepts

• A data structure is a particular way of organizing data in a computer so that it can be used efficiently.[13]
• Data structures can be used to organize the storage and retrieval of information stored in both main memory and secondary memory.[14]
• The array and record data structures are based on computing the addresses of data items with arithmetic operations; while the linked data structures are based on storing addresses of data items within the structure itself.[15]
• An array is a number of elements in a specific order, typically all of the same type. Elements are accessed using an integer index to specify which element is required. Arrays may be fixed-length or resizable.[16]
• A linked list is a linear collection of data elements of any type, called nodes, where each node has itself a value, and points to the next node in the linked list.[17]
• A record (also called tuple or struct) is an aggregate data structure. A record is a value that contains other values, typically in fixed number and sequence and typically indexed by names. The elements of records are usually called fields or members.[18]
• A class is a data structure that contains data fields, like a record, as well as various methods which operate on the contents of the record.[19]

### Python Data Structures

• Python data structures include lists, dictionaries, tuples, and sets.[20]
• Python lists are implemented internally as variable-length arrays, rather than linked lists.[21]
• Python dictionaries are implemented internally as resizable hash tables.[22]
• Python tuples are records.[23]
• Python sets are implemented internally as hash tables (like dictionaries) with optimizations that take advantage of the fact that the values are always None.[24]
• The data types for a list, dictionary, tuple, and set, are 'list', 'dict', 'tuple', and 'set', respectively.[25]
• The list(), dict(), tuple(), and set() functions may be used to create list, dictionary, tuple, and set objects, respectively.[26]
• List and dictionary items are mutable. Tuple and set items are immutable.[27]
• Lists and tuples maintain order. Dictionaries and sets are unordered.[28]
• Lists and tuples allow duplication. Dictionary and set items are unique.[29]
• Sets may be used to remove duplication found in other data structures.[30]
• List, dictionary, tuple, and set items may be accessed using a for loop.[31]
• List and tuple items may be accessed by index. Dictionary items are accessed by key. Set items cannot be accessed by index.[32]
• Python supports having a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time.[33]
• Sets support logical set operations, including membership, subset, superset, union, intersection, and difference.[34]

## Key Terms

comparable
A type where one value can be checked to see if it is greater than, less than, or equal to another value of the same type. Types which are comparable can be put in a list and sorted.[35]
data structure
A collection of related values, often organized in lists, dictionaries, tuples, etc.[36]
DSU
Abbreviation of “decorate-sort-undecorate”, a pattern that involves building a list of tuples, sorting, and extracting part of the result.[37]
gather
The operation of assembling a variable-length argument tuple.[38]
hashable
A type that has a hash function. Immutable types like integers, floats, and strings are hashable; mutable types like lists and dictionaries are not.[39]
scatter
The operation of treating a sequence as a list of arguments.[40]
shape (of a data structure)
A summary of the type, size, and composition of a data structure.[41]
singleton
A list (or other sequence) with a single element.[42]
tuple
An immutable sequence of elements.[43]
tuple assignment
An assignment with a sequence on the right side and a tuple of variables on the left. The right side is evaluated and then its elements are assigned to the variables on the left.[44]

## Review Questions

Click on a question to see the answer.
1. A data structure is _____.
A data structure is a particular way of organizing data in a computer so that it can be used efficiently.
2. Data structures can be used to _____.
Data structures can be used to organize the storage and retrieval of information stored in both main memory and secondary memory.
3. The array and record data structures are based on _____; while the linked data structures are based on _____.
The array and record data structures are based on computing the addresses of data items with arithmetic operations; while the linked data structures are based on storing addresses of data items within the structure itself.
4. An array is _____. Elements are accessed using _____. Arrays may be _____.
An array is a number of elements in a specific order, typically all of the same type. Elements are accessed using an integer index to specify which element is required. Arrays may be fixed-length or resizable.
5. A linked list is _____.
A linked list is a linear collection of data elements of any type, called nodes, where each node has itself a value, and points to the next node in the linked list.
6. A record (also called tuple or struct) is _____. The elements of records are usually called _____.
A record (also called tuple or struct) is an aggregate data structure. A record is a value that contains other values, typically in fixed number and sequence and typically indexed by names. The elements of records are usually called fields or members.
7. A class is _____.
A class is a data structure that contains data fields, like a record, as well as various methods which operate on the contents of the record.
8. Python data structures include _____.
Python data structures include lists, dictionaries, tuples, and sets.
9. Python lists are implemented internally as _____.
Python lists are implemented internally as variable-length arrays, rather than linked lists.
10. Python dictionaries are implemented internally as _____.
Python dictionaries are implemented internally as resizable hash tables.
11. Python tuples are _____.
Python tuples are records.
12. Python sets are implemented internally as _____.
Python sets are implemented internally as dictionaries (hash tables) with keys and no values.
13. The data types for a list, dictionary, tuple, and set, are _____.
The data types for a list, dictionary, tuple, and set, are 'list', 'dict', 'tuple', and 'set', respectively.
14. The list(), dict(), tuple(), and set() functions may be used to _____.
The list(), dict(), tuple(), and set() functions may be used to create list, dictionary, tuple, and set objects, respectively.
15. List and dictionary items are _____. Tuple and set items are _____.
List and dictionary items are mutable. Tuple and set items are immutable.
16. Lists and tuples maintain _____. Dictionaries and sets are _____.
Lists and tuples maintain order. Dictionaries and sets are unordered.
17. Lists and tuples allow _____. Dictionary and set items _____.
Lists and tuples allow duplication. Dictionary and set items are unique.
18. Sets may be used to remove _____.
Sets may be used to remove duplication found in other data structures.
19. List, dictionary, tuple, and set items may be accessed using a _____ loop.
List, dictionary, tuple, and set items may be accessed using a for loop.
20. List and tuple items may be accessed by _____. Dictionary items are accessed by _____. Set items _____.
List and tuple items may be accessed by index. Dictionary items are accessed by key. Set items cannot be accessed by index.
21. Python supports having a tuple on the left side of an assignment statement. This allows you to _____.
Python supports having a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time.
22. Sets support logical set operations, including _____.
Sets support logical set operations, including membership, subset, superset, union, intersection, and difference.