Python - Lab3 - Collections
Python - Lab3 - Collections
Explanation:
Tuples are immutable by design. So, you cannot modify them.
Goal:
❖ Converting a list to a tuple.
my_list = ["John", 12, "Sam", True, 50.7]
print("The content of my_list is:")
print(my_list)
# Converting the list to a tuple
my_tuple=tuple(my_list)
print("The content of my_tuple is:")
print(my_tuple)
Expected Output:
The content of my_list is:
['John', 12, 'Sam', True, 50.7]
The content of my_tuple is:
('John', 12, 'Sam', True, 50.7)
Goal:
❖ Reversing a tuple.
my_tuple = (1, 2, 3, 4, 5)
print("The content of my_tuple is:")
print(my_tuple)
print("Reversing the tuple:")
rev_tuple = tuple(reversed(my_tuple))
print("The content of rev_tuple is:")
print(rev_tuple)
Expected Output:
The content of my_tuple is:
(1, 2, 3, 4, 5)
Reversing the tuple:
The content of rev_tuple is:
(5, 4, 3, 2, 1)
Exercise #3 – Working with Dictionaries.
Note: - Now you see the use of another important data type. You call it a dictionary.
- These are some noticeable characteristics of this datatype
=> It is a key-value pair.
=> The keys are unique.
=> Keys and values can be of any type.
=> Dictionaries are indexed through its keys.
- When you create a dictionary, you use codes something like the following (here we have
chosen the variable name as my_dictionary ):
my_dictionary = {1: "John", 2: 12, 3: "Sam", 4: True, 5: 50.7}
- You can see that we put elements inside the curly brackets –{ , } now.
- Let us examine some built-in functions for dictionaries which are as follows.
Goal:
❖ Let us create a dictionary and print the details inside it.
# A dictionary with 5 key-value pair
my_dictionary = {1: "John", 2: 12, 3: "Sam", 4: True, 5: 50.7}
print("The my_dictionary contains:")
print(my_dictionary)
Expected Output:
The my_dictionary contains:
{1: 'John', 2: 12, 3: 'Sam', 4: True, 5: 50.7}
Goal:
❖ Let’s use different types of keys in my_dictionary.
❖ In the following code segment, you’ll see that first three keys are numbers and remaining keys
are strings.
# A dictionary with 5 key-value pair
# Choosing different types of keys in the same dictionary
my_dictionary = {1: "John", 2: 12, 3: "Sam", 'fourth': True, 'fifth': 50.7}
print("The my_dictionary contains:")
print(my_dictionary)
print("----------------")
Expected Output:
The my_dictionary contains:
{1: 'John', 2: 12, 3: 'Sam', 'fourth': True, 'fifth': 50.7}
Goal:
❖ Let’s print values for particular keys in a dictionary.
# I want to print values for particular keys
my_dictionary = {1: "John", 2: 12, 3: "Sam", 'fourth': True, 'fifth': 50.7}
print("The my_dictionary contains:")
print(my_dictionary)
print("Value at key 1:", my_dictionary[1])
print("Value at key 2:", my_dictionary[2])
print("Value at key 3:", my_dictionary[3])
print("Value at key 'fourth':", my_dictionary['fourth'])
print("Value at key 'fifth'::", my_dictionary['fifth'])
Expected Output:
The my_dictionary contains:
{1: 'John', 2: 12, 3: 'Sam', 'fourth': True, 'fifth': 50.7}
Value at key 1: John
Value at key 2: 12
Value at key 3: Sam
Value at key 'fourth': True
Value at key 'fifth':: 50.7
Goal:
❖ Let’s assign different values for the same key in a dictionary and want to see the effect.
❖ We also want to check - how many elements are present in the dictionary?
# If you assign different values for the same keys
# last assigned value will be kept
my_dictionary = {1: "John", 2: "Sam", 3: "Jack",1: "Bob"}
print("The my_dictionary contains:")
print(my_dictionary)
print("Value at key 1:", my_dictionary[1])
print(f"Number of contents:{len(my_dictionary)}")
Expected Output:
The my_dictionary contains:
{1: 'Bob', 2: 'Sam', 3: 'Jack'}
Value at key 1: Bob
Number of contents:3
Exercise #4 – Working with Sets.
Note: - Sets are a special kind of datatype that does not hold duplicate values. You can think of it
as a combination of a list and a dictionary.
- For example, like dictionaries, you use curly brackets { and } but like lists, you do not
have any key-value pair. The following is an example of a set:
my_set1 = {1, 2, 3, "Jack", "Bob"}
- Alternatively, to create a set, you can use the built-in set() function like the following:
myset=set(iterable_element)
- Where “ iterable_element “indicates that you can use something like a list, or a tuple like
the following:
#Alternative way to create a set
#Using a list now to create a set
my_set = set([1, 2, 3, "Jack", "Bob"])
#Using a tuple to create a set
my_set = set((1, 2, 3, "Jack", "Bob"))
- Now go through the following code fragments to get some idea about set data types.
Goal:
❖ Let’s supply duplicate values to sets. Then let’s test whether these sets contain duplicates.
my_set1 = {1, 2, 3, "Jack", 2, "Bob", 3, 1}
print("The my_set1 contains:")
print(my_set1)
my_set2 = {"Sam", "Bob", "Jack", "Sam", "Jack", "Ester"}
print("The my_set2 contains:")
print(my_set2)
Expected Output:
The my_set1 contains:
{1, 2, 3, 'Jack', 'Bob'}
The my_set2 contains:
{'Sam', 'Jack', 'Bob', 'Ester'}
Goal:
❖ Sets are mutable.
❖ In the following example, we add 6 to the list and then remove 2 from the set.
# Sets are mutable
my_set = {1, 2, 3, 4, 5}
#my_set = {}#it is treated as empty dictionary
#my_set=set()#this is ok for an empty set
print("The my_set contains:")
print(my_set)
print("Adding 6 to the set now.")
my_set.add(6)
print("Now the set is:")
print(my_set)
print("Removing 2 from the set now.")
my_set.remove(2)
print("Now the my_set is:")
print(my_set)
Expected Output:
The my_set contains:
{1, 2, 3, 4, 5}
Adding 6 to the set now.
Now the set is:
{1, 2, 3, 4, 5, 6}
Removing 2 from the set now.
Now, the my_set is:
{1, 3, 4, 5, 6}
Goal:
❖ You can iterate over strings. So, you can pass a string argument to the set() function.
# Strings are iterable. So, you can use strings to set().
my_str = "vaskaran"
my_set = set(my_str)
print("The my_set contains:")
print(my_set)
Expected Output:
The my_set contains:
{'n', 's', 'k', 'a', 'v', 'r'}
Goal:
❖ In the previous code segment, you saw that sets are unordered.
❖ Now you see that you cannot access the set elements referring to an index.
❖ Here is an example.
# Sets are unordered. You cannot access the elements by referring to an index
my_set = set([2,"abc",1,5])
print("The my_set contains:")
print(my_set)
print("Trying to access the 0th element.")
print(my_set[0])#error
Expected Output:
The my_set contains:
{1, 2, 5, 'abc'}
Trying to access the 0th element.
Traceback (most recent call last):
File
"path/file.py",
line 59, in <module>
print(my_set[0])#error
TypeError: 'set' object is not subscriptable
Goal:
❖ You cannot access set elements by referring to an index. But You can loop through the elements.
❖ Here is an example.
# You cannot access set elements by referring to an index.
# But You can loop through the elements.
my_set = set([2, "hello", 1, 5])
print("The my_set contains:")
for item in my_set:
print(item)
Expected Output:
The my_set contains:
{1, 2, 'hello', 5}
Trying to access the 0th element.
The my_set contains:
1
2
hello
5
Goal:
❖ Removing an element from a set.
❖ Here let’s see the use of both remove and discard.
❖ The difference is: discard() does not raise an error if the element is not present, but remove()
raises an error in that case.
# Remove an element from a set
my_set = set([1,2,3,4,5])
print("The my_set contains:")
print(my_set)
print("Removing 5 using remove().")
my_set.remove(5)
print("Now the my_set contains:")
print(my_set)
print("Removing 4 now using discard().")
my_set.discard(4)
print("Now the my_set contains:")
print(my_set)
Expected Output:
The my_set contains:
{1, 2, 3, 4, 5}
Removing 5 using remove().
Now the my_set contains:
{1, 2, 3, 4}
Removing 4 now using discard().
Now the my_set contains:
{1, 2, 3}
Exercises
1. Create a list that contains more than 2 elements. Then remove the last two elements from the list.
2. Create a tuple with more than 5 elements. Then print the 3rd element of it. Can you print the 3rd
element from last?
3. Create a tuple with elements 1,2,2,3,4,4,4,5. Then reverse the tuple and print how many times 4
appears in this tuple.
4. How a tuple is different from a list?
5. Predict the output:
my_tuple = (1, 2, 2, 3, 4, 4, 5)
my_set = set(my_tuple)
print("The my_set is:")
print(my_set)
6. Can you get any error for the following code?
my_list=["red", "blue"]
my_set = set(my_list)
print("The my_set is:")
print(my_set)
my_set.discard("green")
7. Create a dictionary and print the details. Can you print the value for a particular key?
Solution to Exercises
1
my_list = ["John", 12, 25, 12,"Sam", True, 50.7]
print("The original list is:")
print(my_list)
#Removing the last two elements from the list
del(my_list[-2:])
print("Now the list is:")
print(my_list)
Output:
The original list is:
['John', 12, 25, 12, 'Sam', True, 50.7]
Now the list is:
['John', 12, 25, 12, 'Sam']
2
my_tuple = ("John", 12, 25, 12, "Sam", True, 50.7)
print("The original tuple is:")
print(my_tuple)
#Printing the 3rd element
print("The third element:")
print(my_tuple[2])
print("The third element from last:")
print(my_tuple[-3])
3
my_tuple = (1, 2, 2, 3, 4, 4, 4, 5)
print("The original tuple is:")
print(my_tuple)
print("The reversed tuple is:")
rev_tuple = tuple(reversed(my_tuple))
print(rev_tuple)
print(f"The number of 4 in this tuple:{rev_tuple.count(4)}")
4
Tuples are immutable but lists are mutable.
5
The my_set is:
{1, 2, 3, 4, 5}
Explanation:
Sets do not contain duplicates.
6
The element “green” is not present in the set. If you use remove() , you see a
KeyError , but discard() does not raise any such error. The discard()
method removes the element if it is present in the set.
7
Try it yourself.