Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
28 views

Chapter-III Data Structures in Python

Python PPT Chapter 3 msbte
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Chapter-III Data Structures in Python

Python PPT Chapter 3 msbte
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 129

PROGRAMMING WITH PYTHON

PWP - 22616

UNIT-III
DATA STRUCTURES IN PYTHON

Mr. Naresh A. Kamble


POINTS TO BE COVERED
• LISTS
• TUPLES
• SETS
• DICTIONARIES

2
LISTS
• DEFINING LISTS

• ACCESSING VALUES IN LISTS

• UDATING LISTS

• BASIC LIST OPERATIONS

• BUILT-IN LIST FUNCTIONS

3
4
LISTS
• LIST

• Lists are used to store multiple items in a single variable.

• Lists are created using square brackets [].

• EXAMPLE

• Mylist = [“John”, ”Alice”, “Bob”, 1, 2, 3]

5
LISTS
• EXAMPLE

6
LISTS
• LIST ITEMS

• ORDERED

• Ordered means that the items have a defined order, and that
order will not change.

• If you add new items to a list, the new items will be placed at
the end of the list.

7
LISTS
• LIST ITEMS

• CHANGEABLE

• The list is changeable, meaning that we can change, add, and


remove items in a list after it has been created.

• ALLOW DUPLICATES

• Since lists are indexed, lists can have items with the same
value.

8
9
LISTS
• EXAMPLE 1 : ADDING MULTIPLE ITEMS TO A LIST

10
11
LISTS
• Lists respond to the + and * operators much like strings; they
mean concatenation and repetition, except that the result is a
new list, not a string.

12
LISTS

13
14
LISTS
• There are total 5 Built-in list functions

• len(list)

• max(list)

• min(list)

• list(seq)

• map(aFunction, aSequence)

15
LISTS
• len(list) – Gives the total length of the list

16
LISTS
• max(list) – Returns item from the list with maximum value

17
LISTS
• min(list) – Returns item from the list with minimum value

18
LISTS
• list(seq) – Returns a tuple into a list

19
LISTS
• map(aFunction, aSequence) – it applies a passed-in function
to each item in an iterable object and returns a list
containing all the function call results.

20
LISTS

21
LISTS

22
23
LISTS
• There are total 8 Built-in list methods (updating) functions
• append()
• count()
• remove()
• extend()
• reverse()
• insert()
• sort()
• pop()
24
LISTS
• append() – it appends an object obj passed to the existing
list.

25
LISTS
• count() – Returns how many times the object obj appears in
the existing list.

26
LISTS
• remove() – removes an object obj from the existing list.

27
LISTS
• extend() – Appends the contents in a sequence seq passed
to the existing list.

28
LISTS
• reverse() – Reverse object in a list

29
LISTS
• insert() – Returns a list with object obj inserted at the given
index

30
LISTS
• sort() – Sorts the item in a list & returns the list. If a function
is provided, it will compare using the function provided.

31
LISTS
• pop() – Removes or returns the last object from the list.

32
LISTS
• EXAMPLES

• Write a python program which accepts a sequence of comma-


separated numbers from user and generate a list and a tuple
with those numbers.

• Write a python program to display the first and last colors


from the input list.

• Write a python program to get a single string from two strings,


separated by a space and swap the first two characters of
each string.
33
LISTS
• EXAMPLES

• Write a python program which accepts a string and prints the


same string for 4 times. Each string should be printed on a
new line.

• Write a python program to accept 3 list as shown below:

• List1 = [‘Hello!’]

• List2 = [‘how are you?’]

• List3 = [‘Have a nice day….’]

34
35
TUPLE
• DEFINING TUPLE

• ACCESSING VALUES IN TUPLE

• BASIC TUPLE OPERATIONS

• BUILT-IN TUPLE FUNCTIONS

36
37
TUPLE
• TUPLE

• A tuple is another sequence of 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 with 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.


38
TUPLE
• TUPLE

• Tuples are used to store multiple items in a single variable.

• Tuple is one of 4 built-in data types in Python used to store


collections of data, the other 3 are List, Set, and Dictionary,
all with different qualities and usage.

• A tuple is a collection which is ordered and unchangeable.

39
TUPLE
• EXAMPLE 1 : REPRESENTING TUPLE

40
TUPLE
• TUPLE ITEMS

• ORDERED

• Ordered means that the items have a defined order, and that
order will not change.

• UNCHANGEABLE

• The tuple is unchangeable, meaning that we cannot change,


add, and remove items in a tuple after it has been created.

41
TUPLE
• TUPLE ITEMS

• ALLOW DUPLICATES

• Since tuple are indexed, tuple can have items with the same
value.

42
43
TUPLE
• EXAMPLE 2 : CREATING TUPLE WITH ONE ITEM

44
TUPLE
• EXAMPLE 3: TUPLE ITEMS – DATA TYPES

45
46
TUPLE
• Tuples respond to the + and * operators much like strings;
they mean concatenation and repetition here too, except that
the result is a new tuple, not a string.

47
TUPLE

48
49
TUPLE
• There are total 5 Built-in list functions

• len(tuple)

• max(tuple)

• min(tuple)

• tuple(seq)

50
TUPLE
• len(tuple) – Gives the total length of the tuple

51
TUPLE
• max(tuple) – Returns item from the tuple with maximum
value

52
TUPLE
• min(tuple) – Returns item from the tuple with minimum
value

53
TUPLE
• tuple(seq) – Returns a list into a tuple

54
SAMPLE PROGRAMS
• Write a python program to accept a filename from the user
and print its extension.

55
GUESS GAME
• Define the range of the numbers. By default, it’s 1-100 but you can change it as you prefer.
• Generate a random integer from the above range (1-100).
• Start the game by displaying the user a message saying “Guess the number from X to Y”. You may update
the message as you wish.
• Initialize a variable to 0 to count the total number of chances that the user has taken to guess the number
correctly.
• Write an infinite loop.
• Ask the user to guess the number.
• If the current guessed number is equal to the randomly generated number, then congratulate the user
with a message as you like. An example would be “-> Hurray! You got it in 5 steps!”.
• Break the loop after congratulating the user.
• If the current guessed number is less than the randomly generated number, then give a message to the
user saying “-> Your number is less than the random number” or a custom message having the same
meaning.
• If the current guessed number is greater than the randomly generated number, then give a message to the
user saying “-> Your number is greater than the random number” or a custom with the same meaning.
• Finally, increment the chances that the user has taken to guess.

56
57
SET
• DEFINING SET

• ACCESSING VALUES IN SET

• UDATING SET

• BASIC SET OPERATIONS

• BUILT-IN SET FUNCTIONS

58
SET
• SET

• A set is an unordered collection of unique items.

• It is defined by separated by comma inside braces {}.

• It can have any number of items and they may be of different


types (integer, float, tuple, string etc.)

• Since items in set are unordered, we cannot perform set


operations like union, intersection, difference on two sets
using indexing and slicing.

59
SET
• EXAMPLE 1 : REPRESENTING SET

60
SET
• SET ITEMS

• UNORDERED

• Unordered means that the items do not have a defined order,


and that order.

• UNCHANGEABLE

• The set is unchangeable, meaning that we cannot change,


add, and remove items in a set after it has been created.

61
SET
• SET ITEMS

• DUPLICATES NOT ALLOWED

• Set cannot have items with the same value.

62
63
SET

64
65
SET
• SET UNION

• SET INTERSECTION

• SET DIFFERENCE

• SET SYMMETERIC DIFFERENCE

66
SET
• SET UNION –union()

• The union of two sets is the set of all the elements of both the
sets without duplicates.

• We can use union() or | symbol to find the set intersection.

67
SET

68
SET
• SET INTERSECTION – intersection()

• The intersection of two sets is the set of all the common


elements of both the sets.

• We can use intersection() or & symbol to find the set


intersection.

69
SET

70
SET
• SET DIFFERENCE – difference()

• The difference of two sets is the set of all the elements that
are not present in second set.

• We can use difference() or - symbol to find the set difference.

71
SET

72
SET
• SET SYMMETRIC DIFFERENCE – symmetric_difference()

• The symmetric difference of two sets is the set of all the


elements that are either in the first set or second set but
both.

• We can use symmetric_difference() or ^ symbol to find the


set symmetric difference.

73
SET

74
75
SET
• SET BUILT IN FUNCTIONS (8)
• len(set)
• max(set)
• min(set)
• sum(set)
• sorted(set)
• enumerate(set)
• any(set)
• all(set)
76
SET
• len(set) – Returns the length or total number of items in a set

77
SET
• max(set) – Returns item from the set with maximum value.

78
SET
• min(set) – Returns item from the set with minimum value.

79
SET
• sum(set) – Returns the sum of all items in the set.

80
SET
• sorted(set) – Returns a new sorted set.

81
SET
• enumerate(set) – Returns an enumerate object. It contains
the index and value of all the items of set as a pair.

82
SET
• any(set) – Returns True, if the set contains at least one item,
false otherwise.

83
SET
• all(set) – Returns True, if all the elements are true or the set is
empty.

84
85
SET
• SET BUILT IN METHODS (11)
• set.add(obj)
• set.remove(obj)
• set.discard(obj)
• set.pop()
• set1.update(set2)
• set1.intersection_update(set2)
• set1. difference_update(set2)
• set1. symmetric_difference_update(set2)
86
SET
• SET BUILT IN METHODS (11)

• set1.isdisjoint(set2)

• set1.issubset(set2)

• set1.issuperset(set2)

87
SET
• set.add(obj) – Adds a element to a set

88
SET
• set.remove(obj) – Removes a element from the set

89
SET
• set.discard(obj) – Discards a element from the set

90
SET
• set.pop(obj) – Removes and returns an arbitrary set element.

91
SET
• set1.update(set2) – Update a set with the union of itself and
others.

92
SET
• set1.intersection_update(set2) – Update a set with the
intersection of itself and other.

93
SET
• set1.difference_update(set2) – Removes all elements of
another set (set2) from current set (set3) and the result is
strode in current set (set1)

94
SET
• set1.symmetric_difference_update(set2) – Update a set with
symmetric difference of itself and another.

95
SET
• set1.isdisjoint(set2) – Returns True if two sets have a null
intersection.

96
SET
• set1.issubset(set2) – Returns True if set1 is subset of set2.

97
SET
• set1.issuperset(set2) – Returns True if set1 is superset of set2.

98
99
DICTIONARY
• DEFINING DICTIONARY

• ACCESSING VALUES IN DICTIONARY

• UDATING DICTIONARY

• BASIC DICTIONARY OPERATIONS

• BUILT-IN DICTIONARY FUNCTIONS

100
DICTIONARY
• DICTIONARY

• Dictionary in Python is an unordered collection of data


values.

• It is used to store data values like a map, which, unlike other


data types that hold only a single value as an element.

• Dictionary holds key : value pair.

• Key-value is provided in the dictionary to make it more


optimized.

101
DICTIONARY
• DICTIONARY

• In Python, a Dictionary can be created by placing a sequence


of elements within curly {} braces, separated by ‘comma’.

• Dictionary holds pairs of values, one being the Key and the
other corresponding pair element being its key : value.

• Values in a dictionary can be of any data type and can be


duplicated, whereas keys can’t be repeated and must be
immutable.

102
DICTIONARY
• EXAMPLE 1 : REPRESENTING DICTIONARY

103
DICTIONARY
• DICTIONARY ITEMS
• ORDERED OR UNORDERED ?
• As of Python version 3.7, dictionaries are ordered. In Python
3.6 and earlier, dictionaries are unordered.

• CHANGEABLE
• The dictionary is changeable, meaning that we can change,
add, and remove items in a dictionary after it has been
created.
104
DICTIONARY
• DICTIONARY ITEMS

• DUPLICATES NOT ALLOWED

• Dictionary cannot have items with the same value.

105
106
DICTIONARY
• DICTIONARY OPERATIONS • DICTIONARY OPERATIONS

• Definition Operations • Immutable Operations


– Empty dictionary {} • These operations allow us to
work with dictionaries without
altering or modifying their
• Mutable Operations
previous definition.
• These operations allow us to – len
work with dictionaries, but – keys
altering or modifying their – values
previous definition. – items
– [] – in
– del – get
– update – set default
107
DICTIONARY
• DEFINITION OPERATIONS

• Empty dictionary {} - Creates an empty dictionary or a


dictionary with some initial values.

108
DICTIONARY
• MUTABLE OPERATIONS

• [ ] - Adds a new pair of key and value to the dictionary, but in case that
the key already exists in the dictionary, we can update the value.

109
DICTIONARY
• MUTABLE OPERATIONS

• del - Del statement can be used to remove an entry (key-value pair) from
a dictionary.

110
DICTIONARY
• MUTABLE OPERATIONS

• update - This method updates a first dictionary with all the key-value
pairs of a second dictionary.

111
DICTIONARY
• IMMUTABLE OPERATIONS

• len - Returns the number of entries (key-value pairs) in a dictionary.

112
DICTIONARY
• IMMUTABLE OPERATIONS

• keys - This method allows you to get all the keys in the dictionary.

113
DICTIONARY
• IMMUTABLE OPERATIONS

• values - This method allows you to obtain all the values stored in a
dictionary.

114
DICTIONARY
• IMMUTABLE OPERATIONS

• items - Returns all the keys and their associated values ​as a sequence of
tuples.

115
DICTIONARY
• IMMUTABLE OPERATIONS

• in - We can use the in method that test whether a key exists in a


dictionary, returns True if a dictionary has a value stored under the given
key and False otherwise.

116
DICTIONARY
• IMMUTABLE OPERATIONS

• get - Returns the value associated with a key if the dictionary contains
that key, in case that the dictionary does not contain the key, you can
specified a second optional argument to return a default value, if the
argument is not included get method will return None.

117
DICTIONARY
• IMMUTABLE OPERATIONS

• setdefault - This method is similar to get method, it returns the value


associated with a key if the dictionary contains that key, but in case that
the dictionary does not contain the key, this method will create a new
element in the dictionary (key-value pair), where the first argument in this
method is the key, and the second argument is the value. The second
argument is optional, but if this is not included, the value will be None.

118
DICTIONARY
• IMMUTABLE OPERATIONS

119
120
DICTIONARY
• BUILT-IN FUNCTIONS

• len(dict)

• str(dict)

• type(variable)

121
DICTIONARY
• BUILT-IN FUNCTIONS

• str(dict) – Produce a printable string representation of the


dictionary.

122
DICTIONARY
• BUILT-IN FUNCTIONS

• type(variable) – It returns the type of the passed variable.

123
124
DICTIONARY
• dict.clear()

• dict.copy()

• dict.keys()

• dict.values()

• dict.items()

• dict1.update(dict2)

• dict.has_key(key)

• dict.get(key,default=None)

• dict.setdefault(key,default=None)

• dict.fromkeys(seq,[val])
125
DICTIONARY
• BUILT-IN METHODS

• dict.clear() – Remove all elements of dictionary.

126
DICTIONARY
• BUILT-IN METHODS

• dict.copy() – Returns a copy of dictionary.

127
DICTIONARY
• BUILT-IN METHODS

• dict.has_key(key) – Returns True if key is present, else False.

128
DICTIONARY
• BUILT-IN METHODS

• dict.fromkeys(seq,[val]) – Creates a new dictionary from


sequence and values.

129

You might also like