Python Programming/Tuples and Sets
This lesson introduces Python tuples and sets by comparing them to lists and dictionaries.
Objectives and Skills
[edit | edit source]Objectives and skills for this lesson include:[1]
- Data Structures
- Tuple
- Sequences
- Set
Readings
[edit | edit source]Multimedia
[edit | edit source]Examples
[edit | edit source]Data Structures
[edit | edit source]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
[edit | edit source]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
[edit | edit source]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
[edit | edit source]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
[edit | edit source]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
[edit | edit source]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
[edit | edit source]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
[edit | edit source]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
[edit | edit source]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
[edit | edit source]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
[edit | edit source]Tutorials
[edit | edit source]- Complete one or more of the following tutorials:
- TutorialsPoint
- Wikibooks
Practice
[edit | edit source]- 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.
- 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.
- 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.
- 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
[edit | edit source]Data Structure Concepts
[edit | edit source]- 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
[edit | edit source]- 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
[edit | edit source]- 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
[edit | edit source]-
A data structure is _____.A data structure is a particular way of organizing data in a computer so that it can be used efficiently.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
Python data structures include _____.Python data structures include lists, dictionaries, tuples, and sets.
-
Python lists are implemented internally as _____.Python lists are implemented internally as variable-length arrays, rather than linked lists.
-
Python dictionaries are implemented internally as _____.Python dictionaries are implemented internally as resizable hash tables.
-
Python tuples are _____.Python tuples are records.
-
Python sets are implemented internally as _____.Python sets are implemented internally as dictionaries (hash tables) with keys and no values.
-
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.
-
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.
-
List and dictionary items are _____. Tuple and set items are _____.List and dictionary items are mutable. Tuple and set items are immutable.
-
Lists and tuples maintain _____. Dictionaries and sets are _____.Lists and tuples maintain order. Dictionaries and sets are unordered.
-
Lists and tuples allow _____. Dictionary and set items _____.Lists and tuples allow duplication. Dictionary and set items are unique.
-
Sets may be used to remove _____.Sets may be used to remove duplication found in other data structures.
-
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.
-
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.
-
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.
-
Sets support logical set operations, including _____.Sets support logical set operations, including membership, subset, superset, union, intersection, and difference.
Assessments
[edit | edit source]- Flashcards: Quizlet: Python Lists and Tuples
- Quiz: Quizlet: Python Lists and Tuples
See Also
[edit | edit source]References
[edit | edit source]- ↑ Vskills: Certified Python Developer
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python 3: Tuples
- ↑ Python.org: Built-in Types
- ↑ Wikipedia: Data structure
- ↑ Wikipedia: Data structure
- ↑ Wikipedia: Data structure
- ↑ Wikipedia: Data structure
- ↑ Wikipedia: Data structure
- ↑ Wikipedia: Data structure
- ↑ Wikipedia: Data structure
- ↑ Python.org: Data Structures
- ↑ Python.org: Design and History FAQ
- ↑ Python.org: Design and History FAQ
- ↑ Python.org: Design and History FAQ
- ↑ Quora: How is set implemented internally in Python
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python 3: Tuples
- ↑ Python.org: Built-in Types
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples
- ↑ PythonLearn: Tuples