🐍 Python Data Structures · Tuple, Set, Dictionary · Taming Python by Programming
PYTHON · DATA STRUCTURES Sections 2.4, 2.5, 2.6
📌 Taming Python by Programming · Chapter 2
📖 Tuple · Set · Dictionary — complete reference with all examples
📚 Dr. Jeeva Jose · Khanna Book Publishing · ISBN: 978-93-86173-34-8
👨‍🏫 Detailed extraction · all functions, methods, frozenset & examples
2.4 TUPLE

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. The main differences between lists and tuples are lists are enclosed in square brackets ([ ]) and their elements and size can be changed, while tuples are enclosed in parentheses (() ) and cannot be updated. Tuples can be considered as read-only lists.

📘 Example Program — tuple basics

first_tuple = ('abcd', 147, 2.43, 'Tom', 74.9) small_tuple = (111, 'Tom') print(first_tuple) # Prints complete tuple print(first_tuple[0]) # Prints first element of the tuple print(first_tuple[1:3]) # Prints elements starting from 2nd till 3rd print(first_tuple[2:]) # Prints elements starting from 3rd element print(small_tuple * 2) # Prints tuple two times print(first_tuple + small_tuple) # Prints concatenated tuples
('abcd', 147, 2.43, 'Tom', 74.9) abcd (147, 2.43) (2.43, 'Tom', 74.9) (111, 'Tom', 111, 'Tom') ('abcd', 147, 2.43, 'Tom', 74.9, 111, 'Tom')

Invalid with tuple (valid with list):

first_list = ['abcd', 147, 2.43, 'Tom', 74.9] first_tuple = ('abcd', 147, 2.43, 'Tom', 74.9) tuple[2] = 100 # Invalid syntax with tuple list[2] = 100 # Valid syntax with list

To delete an entire tuple we can use the del statement. Example del tuple. It is not possible to remove individual items from a tuple. However it is possible to create tuples which contain mutable objects, such as lists.

🧩 Demo — Tuple containing Lists

# Demo of Tuple containing Lists t = ([1,2,3], ['apple','pear','orange']) print(t)
([1, 2, 3], ['apple', 'pear', 'orange'])

It is possible to pack values to a tuple and unpack values from a tuple. We can create tuples even without parenthesis. The reverse operation is called sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence.

📦 Demo — Tuple packing and unpacking

# Demo of Tuple packing and unpacking t = "apple", 1, 100 print(t) x, y, z = t print(x) print(y) print(z)
('apple', 1, 100) apple 1 100

4.1 Built-in Tuple Functions

len(tuple)Gives the total length of the tuple. max(tuple)Returns item from the tuple with maximum value. min(tuple)Returns item from the tuple with minimum value. tuple(seq)Returns a list into a tuple.

🔹 len(tuple) — example

# Demo of len(tuple) tuple1 = ('abcd', 147, 2.43, 'Tom') print(len(tuple1))
4

🔹 max(tuple) — example

# Demo of max(tuple) tuple1 = (1200, 147, 2.43, 1.12) tuple2 = (213, 100, 289) print("Maximum value in:", tuple1, "is", max(tuple1)) print("Maximum value in:", tuple2, "is", max(tuple2))
Maximum value in: (1200, 147, 2.43, 1.12) is 1200 Maximum value in: (213, 100, 289) is 289

🔹 min(tuple) — example

# Demo of min(tuple) tuple1 = (1200, 147, 2.43, 1.12) tuple2 = (213, 100, 289) print("Minimum value in:", tuple1, "is", min(tuple1)) print("Minimum value in:", tuple2, "is", min(tuple2))
Minimum value in: (1200, 147, 2.43, 1.12) is 1.12 Minimum value in: (213, 100, 289) is 100

🔹 tuple(seq) — example

# Demo of tuple(seq) list = ['abcd', 147, 2.43, 'Tom'] print("Tuple:", tuple(list))
Tuple: ('abcd', 147, 2.43, 'Tom')

2.5 SET

Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces {}. It can have any number of items and they may be of different types (integer, float, tuple, string etc.). Items in a set are not ordered. Since they are unordered we cannot access or change an element of set using indexing or slicing. We can perform set operations like union, intersection, difference on two sets. Set have unique values. They eliminate duplicates. The slicing operator [] does not work with sets. An empty set is created by the function set().

🧪 Demo — Set Creation

# Demo of Set Creation s1 = {1, 2, 3} # set of integer numbers print(s1) s2 = {1, 2, 3, 2, 1, 2} # output contains only unique values print(s2) s3 = {1, 2.4, 'apple', 'Tom', 3} # set of mixed data types print(s3) # s4 = {1, 2, [3, 4]} # sets cannot have mutable items # print(s4) # Hence not permitted s5 = set({1, 2, 3, 4}) # using set function to create set from a list print(s5)
{1, 2, 3} {1, 2, 3} {1, 3, 2.4, 'apple', 'Tom'} {1, 2, 3, 4}

2.5.1 Built-in Set Functions

len(set)Returns the length or total number of items in a set. max(set)Returns item from the set with maximum value. min(set)Returns item from the set with minimum value. sum(set)Returns the sum of all items in the set. sorted(set)Returns a new sorted list. The set does not sort itself. enumerate(set)Returns an enumerate object. It contains the index and value of all the items of set as a pair. any(set)Returns True, if the set contains at least one item, False otherwise. all(set)Returns True, if all the elements are true or the set is empty.

🔹 len(set) — example

# Demo of len(set) set1 = {'abcd', 147, 2.43, 'Tom'} print(len(set1))
4

🔹 max(set) — example

# Demo of max(set) set1 = {1200, 147, 2.43, 1.12} set2 = {213, 100, 289} print("Maximum value in:", set1, "is", max(set1)) print("Maximum value in:", set2, "is", max(set2))
Maximum value in: {1200, 1.12, 2.43, 147} is 1200 Maximum value in: {289, 100, 213} is 289

🔹 min(set) — example

# Demo of min(set) set1 = {1200, 147, 2.43, 1.12} set2 = {213, 100, 289} print("Minimum value in:", set1, "is", min(set1)) print("Minimum value in:", set2, "is", min(set2))
Minimum value in: {1200, 1.12, 2.43, 147} is 1.12 Minimum value in: {289, 100, 213} is 100

🔹 sum(set) — example

# Demo of sum(set) set1 = {147, 2.43} set2 = {213, 100, 289} print("Sum of elements in", set1, "is", sum(set1)) print("Sum of elements in", set2, "is", sum(set2))
Sum of elements in {147, 2.43} is 149.43 Sum of elements in {289, 100, 213} is 602

🔹 sorted(set) — example

# Demo of sorted(set) set1 = {213, 100, 289, 40, 23, -1, 1000} set2 = sorted(set1) print("Sum of elements before sorting:", set1) print("Sum of elements after sorting:", set2)
Sum of elements before sorting: {1, 100, 289, 1000, 40, 213, 23} Sum of elements after sorting: {1, 23, 40, 100, 213, 289, 1000}

🔹 enumerate(set) — example

# Demo of enumerate(set) set1 = {213, 100, 289, 40, 23, 1, 1000} print("enumerate(set):", enumerate(set1))
enumerate(set): <enumerate object at 0x7f0a73573690>

🔹 any(set) — example

# Demo of any(set) set1 = set() set2 = {1, 2, 3, 4} print("any(set):", any(set1)) print("any(set):", any(set2))
any(set): False any(set): True

🔹 all(set) — example

# Demo of all(set) set1 = {1, 2, 3} set2 = {0, 2, 3} print("all(set1):", all(set1)) print("all(set2):", all(set2))
all(set1): True all(set2): False

2.5.2 Built-in Set Methods

set.add(obj)Adds an element obj to a set. set.remove(obj)Removes an element obj from the set. Raises KeyError if the set is empty. set.discard(obj)Removes an element obj from the set. Nothing happens if the element to be deleted is not in the set. set.pop()Removes and returns an arbitrary set element. Raises KeyError if the set is empty. set1.union(set2)Returns the union of two sets as a new set. set1.update(set2)Update a set with the union of itself and others. The result will be stored in set1. set1.intersection(set2)Returns the intersection of two sets as a new set. set1.intersection_update()Update the set with the intersection of itself and another. The result will be stored in set1. set1.difference(set2)Returns the difference of two or more sets into a new set. set1.difference_update(set2)Remove all elements of another set set2 from set1 and the result is stored in set1. set1.symmetric_difference(set2)Return the symmetric difference of two sets as a new set. set1.symmetric_difference_update(set2)Update a set with the symmetric difference of itself and another. set1.isdisjoint(set2)Returns True if two sets have a null intersection. set1.issubset(set2)Returns True if set1 is a subset of set2. set1.issuperset(set2)Returns True, if set1 is a super set of set2.

📌 set.add(obj) — example

# Demo of set.add(obj) set1 = {3, 8, 2, 6} print("Set before addition:", set1) set1.add(9) print("Set after addition:", set1)
Set before addition: {8, 2, 3, 6} Set after addition: {8, 9, 2, 3, 6}

📌 set.remove(obj) — example

# Demo of set.remove(obj) set1 = {3, 8, 2, 6} print("Set before deletion:", set1) set1.remove(8) print("Set after deletion:", set1)
Set before deletion: {8, 2, 3, 6} Set after deletion: {2, 3, 6}

📌 set.discard(obj) — example

# Demo of set.discard(obj) set1 = {3, 8, 2, 6} print("Set before discard:", set1) set1.discard(8) print("Set after discard:", set1) # Element is present set1.discard(9) print("Set after discard:", set1) # Element is not present
Set before discard: {8, 2, 3, 6} Set after discard: {2, 3, 6} Set after discard: {2, 3, 6}

📌 set.pop() — example

# Demo of set.pop() set1 = {3, 8, 2, 6} print("Set before pop:", set1) set1.pop() print("Set after popping:", set1)
Set before pop: {8, 2, 3, 6} Set after popping: {2, 3, 6}

📌 set1.union(set2) — example

# Demo of set1.union(set2) set1 = {3, 8, 2, 6} set2 = {4, 2, 1, 9} set3 = set1.union(set2) # Unique values will be taken print("Union:", set3)
Union: {1, 2, 3, 4, 6, 8, 9}

📌 set1.update(set2) — example

# Demo of set1.update(set2) set1 = {3, 8, 2, 6} set2 = {4, 2, 1, 9} set1.update(set2) print("Update Method:", set1)
Update Method: {1, 2, 3, 4, 6, 8, 9}

📌 set1.intersection(set2) — example

# Demo of set1.intersection(set2) set1 = {3, 8, 2, 6} set2 = {4, 2, 1, 9} set3 = set1.intersection(set2) print("Intersection:", set3)
Intersection: {2}

📌 set1.intersection_update() — example

# Demo of set1.intersection_update(set2) set1 = {3, 8, 2, 6} set2 = {4, 2, 1, 9} set1.intersection_update(set2) print("Intersection_update:", set1)
Intersection_update: {2}

📌 set1.difference(set2) — example

# Demo of set1.difference(set2) set1 = {3, 8, 2, 6} set2 = {4, 2, 1, 9} set3 = set1.difference(set2) print("Difference:", set3)
Difference: {8, 3, 6}

📌 set1.difference_update(set2) — example

# Demo of set1.difference_update(set2) set1 = {3, 8, 2, 6} set2 = {4, 2, 1, 9} set1.difference_update(set2) print("Difference Update:", set1)
Difference Update: {8, 3, 6}

📌 set1.symmetric_difference(set2) — example

# Demo of set1.symmetric_difference(set2) set1 = {3, 8, 2, 6} set2 = {4, 2, 1, 9} set3 = set1.symmetric_difference(set2) print("Symmetric Difference :", set3)
Symmetric Difference : {1, 3, 4, 6, 8, 9}

📌 set1.symmetric_difference_update(set2) — example

# Demo of set1.symmetric_difference_update(set2) set1 = {3, 8, 2, 6} set2 = {4, 2, 1, 9} set1.symmetric_difference_update(set2) print("Symmetric Difference Update:", set1)
Symmetric Difference Update: {1, 3, 4, 6, 8, 9}

📌 set1.isdisjoint(set2) — example

# Demo of set1.isdisjoint(set2) set1 = {3, 8, 2, 6} set2 = {4, 7, 1, 9} print("Result of set1.isdisjoint(set2):", set1.isdisjoint(set2))
Result of set1.isdisjoint(set2): True

📌 set1.issubset(set2) — example

# Demo of set1.issubset(set2) set1 = {3, 6} set2 = {3, 8, 4, 7, 1, 9} print("Result of set1.issubset(set2):", set1.issubset(set2))
Result of set1.issubset(set2): True

📌 set1.issuperset(set2) — example

# Demo of set1.issuperset(set2) set1 = {3, 8, 4, 6} set2 = {3, 8} print("Result of set1.issuperset(set2):", set1.issuperset(set2))
Result of set1.issuperset(set2): True

2.5.3 Frozenset

Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once assigned. While tuples are immutable lists, frozensets are immutable sets. Sets being mutable are unhashable, so they can't be used as dictionary keys which will be discussed in the next section. On the other hand, frozensets are hashable and can be used as keys to a dictionary.

Frozensets can be created using the function frozenset(). This datatype supports methods like difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and union(). Being immutable it does not have methods like add(), remove(), update(), difference_update(), intersection_update(), symmetric_difference_update() etc.

❄️ Demo — frozenset()

# Demo of frozenset() set1 = frozenset({3, 8, 4, 6}) print("Set1:", set1) set2 = frozenset({3, 8}) print("Set2:", set2) print("Result of set1.intersection(set2):", set1.intersection(set2))
Set1: frozenset({8, 3, 4, 6}) Set2: frozenset({8, 3}) Result of set1.intersection(set2): frozenset({8, 3})

2.6 DICTIONARY

Dictionary is an unordered collection of key-value pairs. It is generally used when we have a huge amount of data. We must know the key to retrieve the value. In Python, dictionaries are defined within braces {} with each item being a pair in the form key:value. Key and value can be of any type. Keys are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. Dictionaries are sometimes found in other languages as "associative memories" or "associative arrays".

📖 Example Program — dictionary basics

dict = {'one': 'This is one'} dict[2] = "This is two" tinvdict = {'name': 'john', 'code': 6734, 'dept': 'sales'} studentdict = {'name': 'john', 'marks': [35, 80, 90]} print(dict['one']) # Prints value for 'one' key print(dict[2]) # Prints value for 2 key print(tinvdict) # Prints complete dictionary print(tinvdict.keys()) # Prints all the keys print(tinvdict.values()) # Prints all the values print(studentdict)
This is one This is two {'dept': 'sales', 'name': 'john', 'code': 6734} dict_keys(['dept', 'name', 'code']) dict_values(['sales', 'john', 6734]) {'name': 'john', 'marks': [35, 80, 90]}

We can update a dictionary by adding a new key-value pair or modifying an existing entry.

✏️ Demo — updating and adding new values

# Demo of updating and adding new values to dictionary dict1 = {'Name': 'Tom', 'Age': 20, 'Height': 160} print(dict1) dict1['Age'] = 25 # updating existing value in Key-Value pair print("Dictionary after update:", dict1) dict1['Weight'] = 60 # Adding new Key-value pair print("Dictionary after adding new Key-value pair:", dict1)
{'Name': 'Tom', 'Age': 20, 'Height': 160} Dictionary after update: {'Name': 'Tom', 'Age': 25, 'Height': 160} Dictionary after adding new Key-value pair: {'Name': 'Tom', 'Age': 25, 'Height': 160, 'Weight': 60}

We can delete the entire dictionary elements or individual elements in a dictionary. We can use del statement to delete the dictionary completely. To remove entire elements of a dictionary, we can use the clear() method which will be discussed in the built-in methods of dictionary.

🗑️ Demo — Deleting Dictionary

# Demo of Deleting Dictionary dict1 = {'Name': 'Tom', 'Age': 20, 'Height': 160} print(dict1) del dict1['Age'] # deleting Key-value pair 'Age': 20 print("Dictionary after deletion:", dict1) dict1.clear() # Clearing entire dictionary print(dict1)
{'Name': 'Tom', 'Age': 20, 'Height': 160} Dictionary after deletion: {'Name': 'Tom', 'Height': 160} {}

Properties of Dictionary Keys

  1. More than one entry per key is not allowed, no duplicate key is allowed. When duplicate keys are encountered during assignment, the last assignment is taken.
  2. Keys are immutable. This means keys can be numbers, strings or tuple. But it does not permit mutable objects like lists.

2.6.1 Built-in Dictionary Functions

len(dict)Gives the length of the dictionary. str(dict)Produces a printable string representation of the dictionary. type(variable)The method type() returns the type of the passed variable. If passed variable is dictionary then it would return a dictionary type.

🔹 len(dict) — example

# Demo of len(dict) dict1 = {'Name':'Tom', 'Age':20, 'Height':160} print(dict1) print("Length of Dictionary =", len(dict1))
{'Name': 'Tom', 'Age': 20, 'Height': 160} Length of Dictionary = 3

🔹 str(dict) — example

# Demo of str(dict) dict1 = {'Name':'Tom', 'Age':20, 'Height':160} print(dict1) print("Representation of Dictionary =", str(dict1))
{'Name': 'Tom', 'Age': 20, 'Height': 160} Representation of Dictionary = {'Name': 'Tom', 'Age': 20, 'Height': 160}

🔹 type(variable) — example

# Demo of type(variable) dict1 = {'Name':'Tom', 'Age':20, 'Height':160} print(dict1) print("Type(variable) =", type(dict1)) s = "abcde" print("Type(variable) =", type(s)) list1 = [1,'a',23,'Tom'] print("Type(variable) =", type(list1))
{'Name': 'Tom', 'Age': 20, 'Height': 160} Type(variable) = <class 'dict'> Type(variable) = <class 'str'> Type(variable) = <class 'list'>

2.6.2 Built-in Dictionary Methods

dict.clear()Removes all elements of dictionary dict. dict.copy()Returns a copy of the dictionary dict. dict.keys()Returns a list of keys in dictionary dict. dict.values()Returns list of all values available in a dictionary. dict.items()Returns a list of dictionary dict's (key, value) tuple pairs. dict1.update(dict2)The dictionary dict2's key-value pair will be updated in dictionary dict1. dict.get(key, default=None)Returns the value corresponding to the key specified and if the key specified is not in the dictionary, it returns the default value. dict.setdefault(key, default=None)Similar to dict.get() but will set the key with the value passed and if key is not in the dictionary, it will set with the default value. dict.fromkeys(seq,[val])Creates a new dictionary from sequence seq and values from val.

📌 dict.clear() — example

# Demo of dict.clear() dict1 = {'Name':'Tom', 'Age':20, 'Height':160} print(dict1) dict1.clear() print(dict1)
{'Name': 'Tom', 'Age': 20, 'Height': 160} {}

📌 dict.copy() — example

# Demo of dict.copy() dict1 = {'Name':'Tom', 'Age':20, 'Height':160} print(dict1) dict2 = dict1.copy() print(dict2)
{'Name': 'Tom', 'Age': 20, 'Height': 160} {'Name': 'Tom', 'Age': 20, 'Height': 160}

📌 dict.keys() — example

# Demo of dict.keys() dict1 = {'Name':'Tom', 'Age':20, 'Height':160} print(dict1) print("Keys in Dictionary:", dict1.keys())
{'Name': 'Tom', 'Age': 20, 'Height': 160} Keys in Dictionary: dict_keys(['Name', 'Age', 'Height'])

Keys in sorted order:

# Demo of dict.keys() in sorted order dict1 = {'Name':'Tom', 'Age':20, 'Height':160} print(dict1) print("Keys in sorted order:", sorted(dict1.keys()))
{'Name': 'Tom', 'Age': 20, 'Height': 160} Keys in sorted order: ['Age', 'Height', 'Name']

📌 dict.values() — example

# Demo of dict.values() dict1 = {'Name':'Tom', 'Age':20, 'Height':160} print(dict1) print("Values in Dictionary:", dict1.values())
{'Name': 'Tom', 'Age': 20, 'Height': 160} Values in Dictionary: dict_values(['Tom', 20, 160])

Values in sorted order:

# Demo of dict.values() in sorted order dict1 = {'Height':160, 'Age':20, 'Weight':60} print(dict1) print("Values in sorted order:", sorted(dict1.values()))
{'Height': 160, 'Age': 20, 'Weight': 60} Values in sorted order: [20, 60, 160]

📌 dict.items() — example

# Demo of dict.items() dict1 = {'Name':'Tom', 'Age':20, 'Height':160} print(dict1) print("Items in Dictionary:", dict1.items())
{'Name': 'Tom', 'Age': 20, 'Height': 160} Items in Dictionary: dict_items([('Name', 'Tom'), ('Age', 20), ('Height', 160)])

📌 dict1.update(dict2) — example

# Demo of dict1.update(dict2) dict1 = {'Name':'Tom', 'Age':20, 'Height':160} dict2 = {'Weight':60} dict1.update(dict2) print("Dict1 updated Dict2 :", dict1)
Dict1 updated Dict2 : {'Name': 'Tom', 'Age': 20, 'Height': 160, 'Weight': 60}

📌 dict.get(key, default=None) — example

# Demo of dict.get(key, default='Name') dict1 = {'Name':'Tom', 'Age':20, 'Height':160} print(dict1) print("Dict1.get('Age'):", dict1.get('Age')) print("Dict1.get('Phone'):", dict1.get('Phone', 0)) # 'Phone' not a key, hence 0 is given as default
{'Name': 'Tom', 'Age': 20, 'Height': 160} Dict1.get('Age'): 20 Dict1.get('Phone'): 0

📌 dict.setdefault(key, default=None) — example

# Demo of dict.setdefault(key, default='Name') dict1 = {'Name':'Tom', 'Age':20, 'Height':160} print(dict1) print("Dict1.setdefault('Age'):", dict1.setdefault('Age')) print("Dict1.setdefault('Phone'):", dict1.setdefault('Phone', 0)) # 'Phone' not a key, hence 0 is given as default value.
{'Name': 'Tom', 'Age': 20, 'Height': 160} Dict1.setdefault('Age'): 20 Dict1.setdefault('Phone'): 0

📌 dict.fromkeys(seq,[val]) — example

# Demo of dict.fromkeys(seq,[val]) list = {'Name', 'Age', 'Height'} dict = dict.fromkeys(list) print('New Dictionary:', dict)
New Dictionary: {'Name': None, 'Age': None, 'Height': None}
📖 Reference: Dr. Jeeva Jose, Taming Python by Programming, Khanna Book Publishing, Chapter 2 (Sections 2.4, 2.5, 2.6).
🐍 Complete extraction · all examples, functions, methods & frozenset