Module_3
Module_3
ØThere is no cap on the number of sub-lists that can be encapsulated in a single list.
§A list can store elements of different types (integer, float, string, etc.) and can store duplicate
elements
§ Lists are ordered collections with unique indexes for each item.
§ We can access the items in the list using this index number.
§To access the elements in the list from left to right, the index value starts from zero to (length of the list-1) can
be used.
• Accessing values of elements in a list
•To access an element , use brackets
Value[x]=0
Element = values[x]
# Output
['Jessa', 12.5, 'Emma']
• We can also use slicing a list such as
§Extract a portion of the list
§Reverse a list
§Slicing with a step
§Slice without specifying start or end position
• Syntax: list1*Number
Repetition (*) operator
• Example for replication (*) operator
– print(“Python" * 3)
• #PythonPythonPython
– print(3 * "Hi")
• #HiHiHi
– print("7" * 3)
• #777
== operator for equality testing
• Python allows the comparison of two lists to see if they are exactly equal, meaning they
have the same elements, in the same order by using the “==“ operator.
– Tuples are immutable and hence can be use as keys for the dictionary
– Ordered: Tuples are part of sequence data types, which means they hold the order of the data insertion. It
maintains the index value for each item.
– Immutable :Tuples are unchangeable, which means that we cannot add or delete items to
the tuple after creation.
– Heterogeneous: Tuples are a sequence of data of different data types (like integer, float, list, string, etc;) and
can be accessed through indexing and slicing.
– Contains Duplicates: Tuples can contain duplicates, which means they can have items with
the same value.
– Iteration of tuples, compared to lists is considerably faster.
– Tuples are efficient.
Tuples
• Why tuples prefered over Lists?
– Lists and tuples are both utilized in contexts that are analogous to one another.
• Similarities between Lists and Tuples
– Hold heterogeneous types
– Can have duplicate elements
– Elements can accessed using indexing and slicing
– Both have many functions such as max,min,and len
• Dissimilarities between Lists and Tuples
Lists Tuples
Lists are mutable Tuples are immutable
Lists elements are enclosed by square brackets Tuples are items that are separated by commas
enclosed by brackets()
Lists elements can be accessed using many functions Tuples elements too can be accessed by many
and methods functions and methods, but in lesser, because tuples
are immutable.
Tuples
• Creating a Tuples
– We can create a tuple using the two ways
– Using parenthesis (): A tuple is created by enclosing comma-separated items inside rounded
brackets.
– Syntax: Variable_Name = (<element1>,<element2>,…<elementn>)
– Using a tuple() constructor: Create a tuple by passing the comma-separated items inside
the tuple().
Syntax:Variable_Name=tuple(<sequence>)
Creating a Tuples
• Create a tuple using ()
# number tuple
number_tuple = (10, 20, 25.75)
print(number_tuple)
Print(type(number_tuple))
# Output (10, 20, 25.75)
<class ‘tuple’>
# string tuple
string_tuple = ('Jessa', 'Emma', 'Kelly')
print(string_tuple)
# Output ('Jessa', 'Emma', 'Kelly')
• Using indexing: Access any item from a tuple using its index number
• Using slicing: Access a range of items from a tuple
Indexing and slicing in a Tuple
• Indexing:
– We can access an item of a tuple by using its index number inside the index
operator [] and this process is called “Indexing”.
Example:
tuple1 = ('P', 'Y', 'T', 'H', 'O', 'N')
for i in range(4):
print(tuple1[i])
#Output
P
Y
T
H
•
• Illustration of IndexError
– Tuple1= (1,3,4)
– Tuple1[6]
# output: IndexError:tuple index out of range
• Negative Indexing
– The index values can also be negative, with the last but the first items having the index value as -1
and second last -2 and so on.
– Example:
tuple1 = ('P', 'Y', 'T', 'H', 'O', 'N')
# Negative indexing
# print last item of a tuple
print(tuple1[-1])
#N
# print second last
print(tuple1[-2])
#O
• Slicing:
– We can even specify a range of items to be accessed from a tuple using the technique called
‘Slicing.’
– The operator used is ':'.
– Syntax:
• Tuple_variable[start:stop:step] or
• Tuple_variable[start:stop]
• Example:
• tuple1 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
• # slice a tuple with start and end index number
• print(tuple1[1:5])
• # Output (1, 2, 3, 4)
• # slice a tuple without start index
tuple1 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(tuple1[:5])
# Output (0, 1, 2, 3, 4)
– >>> t = (1, 2, 3, 6, 7, 8)
– >>> 2 not in t
– >>> 5 not in t
• False
• True
Sets
• Introduction to sets:
– A set in Python is a Python data structure that stores a collection of
unique elements.
– Python set is similar mathematical sets, but they are part of the
Python standard library.
Characteristics of a Sets
– Unordered:
• The items in the set are unordered, unlike lists, i.e., it will not maintain the order in
which the items are inserted. The items will be in a different order each time when
we access the Set object.
– Unchangeable:
• Set items must be immutable. We cannot change the set items, i.e., We cannot
modify the items’ value.
• But we can add or remove items to the Set. A set itself may be modified, but the
elements contained in the set must be of an immutable type.
• Lists can’t be set elements, but tuples can.
– Unique:
• There cannot be two items with the same value in the set.Iin set duplicate items
not allowed
– Set does not support indexing
Advantages of Sets
• Sets have a solid mathematical foundation, such as set union and
set intersection.
• Searching for an element in a list takes lots of time. But searching
for element in sets is quickly.
• Sets not allow duplicate elements, like list. So does not effect the
application.
Creating a Set
• Using curly brackets:
• Python sets are constructed by just enclosing all the data
items inside the curly brackets {}.
• The individual values are comma-separated.
• Syntax:
Set_variable = {<element>, <element>,…. <element>}
– Set items are unordered, unchangeable, and do not allow duplicate
values.
Creating a Set
• Example1:
>>>s1 = {}
>>>Type(s1)
Output:
<class ‘dict’>
• Example2:
# set of mixed types intger, string, and floats
>>>sample_set = {'Mark', 'Jessa', 25, 75.25}
>>>print(sample_set)
# Output:
{25, 'Mark', 75.25, 'Jessa'}
Creating a Set
• Using set() constructor:
– The set object is of type class 'set'.
– Create a set by calling the constructor of class ‘set’.
– The items we pass while calling are of the type iterable.
– We can pass items to the set constructor inside double-rounded brackets.
§ Example:
# create a set using set constructor
book_set = set(("Harry Potter", "Angels and Demons", "Atlas Shrugged"))
print(book_set)
§ # output
{'Harry Potter', 'Atlas Shrugged', 'Angels and Demons'}
Creating a Set
• Examples of sets:
– A set created from tuples: st_1 =set((‘tiger’,’lion’))
o/p:{‘tiger’,’lion’}
– A set created from strings: ss_2 = ‘ heeello’
set (ss_2)
o/p: {'h', 'o', 'l', 'e'}(removes duplicate)
– A set with range()function:
>>>X = set(range(0,122,10))
>>>print(X)
o/p: {0, 100, 70, 40, 10, 110, 80, 50, 20, 120, 90, 60, 30}
Basic operations in Sets:
• All the operations that could be performed in a mathematical set
could be done with Python sets.
• We can perform set operations using the operator or the built-in
methods defined in Python for the Set.
– The length or size of the set is determined by using the built –in len() function.
– Syntax: len(set_variable)
– Example:
>>>color_set = {'violet', 'indigo', 'blue', 'green', 'yellow‘}
>>>print(len(color_set))
Output:
5
Membership operator in set
• Example:
>>>color_set = {'violet', 'indigo', 'blue', 'green', 'yellow'}
>>>'violet‘ in color_set
True
>>>’tiger’ not in color_set
True
Sets and frozen sets
Adding elements to sets
• To add one item to a set use the add() method.
• Syntax : set_variable.add(<iterator>)
• The function returns no value. It is added if the specified value
does not exist in the set
• Example:
>>>thisset = {"apple", "banana", "cherry"}
>>>thisset.add("orange")
print(thisset)
O/P: {"apple", "banana", "cherry“, ”orange”}
Adding elements to sets
• To add items from another set into the current set, use
the update() method.
• Syntax: set_variable.update(iterable)
• Example:
>>>thisset = {"apple", "banana", "cherry"}
>>>tropical = {"pineapple", "mango", "papaya"}
>>>thisset.update(tropical)
print(thisset)
O/P: {'apple', 'mango', 'cherry', 'pineapple', 'banana', 'papaya'}
Deletion of elements from Set
• Four methods to the deletion of elements in sets
Deletion of elements from Set
• Removal of an element in set:
– The remove(element) removes specific element and returns it.
– If specified element is not present in the set the method raises an keyError
exception.
– Case sensitive: element name should as same as in set
• Syntax: set_variable.remove(element)
• Example:
– tropical = {"pineapple", "mango", "papaya"}
– tropical.remove(“mango”)
– print(tropical)
– {"pineapple“, "papaya"}
Deletion of elements from Set
• Discarding an element in a set:
– The method discard() is used to discard an element of the set similar to the
remove ().
– It does not raise an error, and the set remains unchanged if element does not
exist in set.
• Syntax: set_variable.discard(element)
– Example:
– X = {1,8,90,100}
– X.discard(100)
– X
– {8,1,90}
Deletion of elements from Set
• Removing a random element in a set
– The method pop() has no input parameters and returns a random
element and removed element or typeError if the set is empty.
– Syntax: set_variable.pop(element)
– Example:
– >>>X = {1,8,90,100}
– >>>item=X.pop()
– >>>item
– Output: 8
Deletion of elements from Set
• Deletion of a set:
– A set deletion can be done using the set clear methd.
– Syntax: set_variable.clear()
– The method removes all the elements from the set.
– It does not take any parameters or return any values.
– Example:
– tropical = {"pineapple", "mango", "papaya"}
– tropical.clear()
– tropical
– o/p:set()
Deletion of elements from Set
• Set copy:
– The set.copy() method returns a shallow copy of the set.
– The result is superficial replica of the set.
– Also use = operator
• Syntax: set_variable1.copy(set_variable2)
– Example:
– >>>X = {1,8,90,100}
– >>>Y= X.copy()
– >>>Y
– O/P: {1,8,90,100}
– >>>Z=X
– >>>Z
– {1,8,90,100}
Introduction to Dictionary
• What is “Dictionary”?
– A kind of associative array that is useful for lookup.
– It is a collection of unorganized items.
– It has a key-value pair for an element.
• Example: Telephone directory, to find the phone number(value) when we know the
name(Key) associated with it.
• Can get all the values in a single go using method listed below:
– dict.keys() isolates keys
– dict.values() isolates values
– dict.items() returns items in a list format of (key,value) tuple pair
Basic dictionary operations
• Example for Membership operator
>>>d_state={1:’Delhi’, 2:’Mumbai’,3:’Chennai’,4:’Kolkatta’}
>>>1 in d_state
Output: True
dict.items()
>>>d_state={1:’Delhi’, 2:’Mumbai’,3:’Chennai’,4:’Kolkatta’}
>>>d_state.items()
o/p:dict_items([(1, 'Delhi'), (2, 'Mumbai'), (3, 'Chennai'), (4, 'Kolkatta')])
Operation on Python dictionary
• Adding an element
– We can add new items to the dictionary using the following two ways.
1.Using key-value assignment: Using a simple assignment statement where value can be assigned directly to
the new key.
• Syntax: dict[key] = value
2.Using update() Method: In this method, the item passed inside the update() method will be inserted into
the dictionary. The item can be another dictionary or any iterable like a tuple of key-value pairs.
• Syntax: dict.update([other]) or dict.update(dict2)
Operation on Python dictionary
Example: 1.Using key-value assignment
>>>person = {"name": "Jessa", 'country': "USA", "telephone": 1178}
# update dictionary by adding 2 new keys
>>> person["weight"] = 50 # using new key
>>>person. update({"height": 6}) # using update method
– Example:
>>>person={'name': 'Jessa', 'country': 'USA', 'weight': 50}
# delete key 'weight'
>>>del person['weight']
# display updated dictionary
>>>print(person)
# Output {'name': 'Jessa', 'country': 'USA'}
>>>del person
print(person)
Output: NameError
Remove the elements of the dictionary
#given dictionary
dict1={1:'a',2:'b',3:[11,22,33]}
print("Given Dictionary:",dict1)
#new dictionary Output:
dict2=dict1 #copying using = operator Given Dictionary: {1: 'a', 2: 'b', 3: [11, 22, 33]}
print("New copy:",dict2)
New copy: {1: 'a', 2: 'b', 3: [11, 22, 33]}
#Updating dict2 elements and checking
the change in dict1 Updated copy: {1: 33, 2: 'b', 3: [11, 22, '44']}
Given Dictionary {1: 33, 2: 'b', 3: [11, 22,
dict2[1]=33
'44']}
dict2[3][2]='44' #list item updated
print("Updated copy:",dict2)
print("Given Dictionary:",dict1)
Copying the elements of the dictionary
• 3.Dictionary.copy():
#given dictionary
dict1={ 10:'a', 20:[1,2,3], 30: 'c'}
print("Given Dictionary:",dict1) Output:
#new dictionary
dict2=dict1.copy() #copying using copy() Given Dictionary: {10: 'a', 20: [1, 2, 3], 30: 'c'}
method New copy: {10: 'a', 20: [1, 2, 3], 30: 'c'}
print("New copy:",dict2)
Updated copy: {10: 10, 20: [1, 2, '45'], 30: 'c'}
Given Dictionary: {10: 'a', 20: [1, 2, '45'], 30: 'c'}
#Updating dict2 elements and checking the
change in dict1
dict2[10]=10
dict2[20][2]='45' #list item updated
print("Updated copy:",dict2)
print("Given Dictionary:",dict1)
Sort dictionary
• The built-in method sorted() will sort the keys in the dictionary and returns a sorted list.
• In case we want to sort the values we can first get the values using the values() and then
sort them.
• The sorted() function takes an iterable as the main argument, with two optional keyword-
only arguments—a key function and a reverse Boolean value.
– Syntax: sorted(iterable[,key=None][,reverse=False])
• Key(optional):- A function to specify the criteria for sorting (e.g., by keys, by values).
i.e normal function identifier or a lambda function(anonymous function)
• Reverse(optional):- If set to True, sorts in descending order. And reverse= False just
sort in ascending order
Sort dictionary
Example:
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 7, "Best" : 2, "for" : 9, "geeks" : 8}
# using items() to get all items
# lambda function is passed in key to perform sort by key
# passing 2nd element of items()
# adding "reversed = True" for reversed order
res = {key: val for key, val in sorted(test_dict.items(), key = lambda x: x[1], reverse = True)}
# printing result
print("Result dictionary sorted by values ( in reversed order ) : " + str(res))
o/p:
Result dictionary sorted by values ( in reversed order ):{'for': 9, 'geeks': 8, 'is': 7, 'Gfg': 5, 'Best': 2}
Example 1: Sorting by Keys (Default)
• In this example, sorted() only returns a sorted list of keys, not the
dictionary itself.
Example 2: Sorting Dictionary Items by Keys
• To sort a dictionary by its keys and keep both keys and values, you can use the
items() method.
Example 3: Sorting by Values
• To sort by values, you can use the key argument.
• To sort by keys:-
Note:
• The key=lambda item: item[1] tells Python to sort based on the
second item in each key-value pair, which are the values.
Example 4: Sorting in Reverse Order
• You can use the reverse=True parameter to sort in descending order.
Nested Dictionaries
• A dictionary can contain dictionaries, this is called nested dictionaries.
Access Items in Nested Dictionaries
• To access items from a nested dictionary, you use the name of the dictionaries,
starting with the outer dictionary:
• Example: Print the name of child 2:
•Nested dictionaries are dictionaries that have one or more dictionaries as their
members. It is a collection of many dictionaries in one dictionary.
# address dictionary to store person address