5 python data structures (array).pptx
Document Details
Uploaded by AffablePhosphorus1665
Bulacan State University
Full Transcript
Data Structures Arrays in python? Engr. Hiroyoshi DG. Arai Data Structures A data structure is a way of organizing and storing data in a computer so that it can be accessed and used efficiently. It provides a way of representing data for manipulation such performing opera...
Data Structures Arrays in python? Engr. Hiroyoshi DG. Arai Data Structures A data structure is a way of organizing and storing data in a computer so that it can be accessed and used efficiently. It provides a way of representing data for manipulation such performing operations on the said data. In other words, a container to contain multiple data. Data Structures In python, there are four built-in data structures – List – Tuple – Set – Dictionary Data Structures Different types of data structures are suited to different kinds of applications. Depending on the nature of the application for data, one data structure can be better than the other. Python Data Types Text Data Type: Mapping Type: – String (str) – Dictionary {dict} Numeric Data Type: Set Types: – Integer (int) – Set {set} – Float (float) – Frozen Set (frozenset) – Complex (complex) Binary Types: Boolean Type: – – Bytes (bytes) Boolean (bool) – Byte Array (bytearray) Sequence Types: – – Memory View (memoryview) List [list] – Tuple (tuple) None Type: – Range (range) – None (None) List It is a collection of ordered and mutable elements. It is represented by square brackets []. It can store elements of different data types. >>> variableName = [element1, element2, … , elementn] Tuple It is a collection of ordered but immutable elements. It is represented by parenthesis (). It can store elements of different data types. >>> variableName = (element1, element2, … , elementn) Set It is a collection of unordered and immutable unique elements. It is represented by curly braces {}. It can store elements of different data types. >>> variableName = {element1, element2, … , elementn} Dictionary It is a collection of ordered(3.7) and mutable key:value pair of elements. It is represented by curly braces {}. It can store elements of different data types. >>> variableName = {key1 : element1, key2: element2} List Data Structures List Tuple Set Dictionary Ordered Ordered Unordere Ordered Mutable Immutabl d Mutable Square e Immutabl Curly Bracket [] Parenthe e Braces {} sis () Curly Key:Value Braces {} Pairs Unique Elements Creating list >>> list_str = [“Adam”, “Bob”, “Chris”, “David”, “Eve”] >>> list_int = [30, 50, 12, 60, 23, 50] >>> list_bool = [True, True, False, True, False] >>> list_float = [2.51, 62.3, 61.6234, 52.31] >>> list_mixed = [“Apple”, 11, False, “Banana”, 5.23] >>> #We can print the list by using the print() function >>> print(list_str) Lists are ordered >>> staff = [“Adam”, “Bob”, “Chris”, “David”, “Eve”] >>> print(staff) [“Adam”, “Bob”, “Chris”, “David”, “Eve”] >>> Accessing List Elements >>> staff = [“Adam”, “Bob”, “Chris”, “David”, “Eve”] >>> print(staff) Chris >>> print(staff[1:3]) [‘Bob’, ‘Chris’] >>> print(staff[::2]) [‘Adam’, ‘Chris’, ‘Eve’] >>> print(staff[-1]) Eve Lists are mutable. We can change its elements >>> staff = [“Adam”, “Bob”, “Chris”, “David”, “Eve”] >>> staff = “Bonnie” >>> print(staff) [“Adam”, “Bonnie”, “Chris”, “David”, “Eve”] >>> staff[2:4] = [“Cory”, “Dante”] >>> print(staff) [“Adam”, “Bonnie”, “Cory”, “Dante”, “Eve”] >>> staff[1:4] = [“Bass”] >>> print(staff) [“Adam”, “Bass”, “Eve”] Inserting elements in the list.append(item) method used for adding and item at the end of the list..insert(index, item) method used for inserting an item at a specified index.extend(iterable) method used to add any iterable to the list Inserting elements in the list >>> my_list = [“Apple”, “Banana”, “Cherry”] >>> my_list2 = [“Mango”, “Grapes”] >>> my_list.append(“Strawberry”) >>> print(my_list) [“Apple”, “Banana”, “Cherry”, “Strawberry”] >>> my_list.insert(2, “Watermelon”) >>> print(my_list) [“Apple”, “Banana”, “Watermelon”, “Cherry”, “Strawberry”] >>> my_list.extend(my_list2) >>> print(my_list) Removing elements in the list.remove(item) method used for removing a specified item in the list.pop(index) method used for removing an item from the specified index in the list. If index is not specified, it removes the last element. It also returns the removed object. Removing elements in the list >>> fruits = [“Apple”, “Banana”, “Cherry”, “Strawberry”] >>> fruits.remove(“Cherry”) >>> print(fruits) [“Apple”, “Banana”, “Strawberry”] >>> fruits.pop() ‘Strawberry’ >>> print(fruits) [“Apple”, “Banana”] >>> fruits.pop(0) ‘Apple’ >>> print(fruits) [“Banana”] Using the returned value of pop() >>> class1a = [“Gahisan”, “Cajefe”, “Acopio”, “Ogoy”] >>> class1b = [“Japa”, “Chan”, “Flores”] >>> student = class1a.pop() >>> class1b.append(student) >>> print(class1a) [“Gahisan”, “Cajefe”, “Acopio”] >>> print(class1b) [“Japa”, “Chan”, “Flores”, “Ogoy”] Sorting List.sort() method used to sort the items in the list alphanumerically, ascending, by default..sort(reverse=True) sort in descending order..reverse() method used to reverse the items in the list. Sorting List >>> car = [“Toyota”, “Honda”, “Tesla”, “BWM”, “Mazda”] >>> modelno = [509531, 663143, 321135, 733324, 612351] >>> name = [“Allan”, “Juan”, “Bernard”, “Vince”] >>> car.sort() >>> print(car) ['BWM', 'Honda', 'Mazda', 'Tesla', 'Toyota’] >>> modelno.sort(reverse=True) >>> print(modelno) [733324, 663143, 612351, 509531, 321135] >>> name.reverse() >>> print(name) ['Vince', 'Bernard', 'Juan', 'Allan'] Copy List Creating a new variable and assigning it to a list is possible but is not a correct way to copy list, because both variables will just reference to the same list and the changes made on the new list will affect the first list or vice versa. Copy List >>> letters = [“a”, “b”, “c”] >>> new_letters = letters >>> print(letters) [“a”, “b”, “c”] >>> print(new_letters) [“a”, “b”, “c”] >>> new_letters.append(“d”) >>> print(letters) [“a”,”b”,”c”,”d”] Copy List To counter this, we need to use a method or a function..copy(list) method for copying a list to a new variable. list(item) function to basically create a new list of the items. Copy List >>> letters = [“a”, “b”, “c”] >>> new_letters = letters.copy() >>> new_letters.append(“d”) >>> print(letters) [“a”, “b”, “c”] >>> print(new_letters) [“a”, “b”, “c”, “d”] Copy List >>> letters = [“a”, “b”, “c”] >>> new_letters = list(letters) >>> new_letters.append(“f”) >>> print(letters) [“a”, “b”, “c”] >>> print(new_letters) [“a”, “b”, “c”, “f”] Length of iterables It is possible to get the length of any iterables that can be used in the logic of the code. len(iterable) function that will return the length of the iterable in integer. Length of iterables >>> my_name = “Hiroyoshi” >>> len(my_name) 9 >>> greek = [“Alpha”, “Beta”, “Omega”] >>> len(greek) 3 Checking Membership >>> console = [“Nintendo”, “Sony”, “Microsoft”] >>> “Sega” in console False >>> “Nintendo” in console True >>> if “Nintendo” in console:... print(“Found it in the list”)... Found it in the list Looping Through a List >>> games = [“Valo”, “ML”, “CS”, “DotA”, “LoL”] >>> for game in games:... print(f“Currently playing {game}.”)... Currently playing Valo. Currently playing ML. Currently playing CS. Currently playing DotA. Currently Playing LoL. >>> Tuple Data Structures List Tuple Set Dictionary Ordered Ordered Unordere Ordered Mutable Immutabl d Mutable Square e Immutabl Curly Bracket [] Parenthe e Braces {} sis () Curly Key:Value Braces {} Pairs Unique Elements Creating Tuple >>> tuple_str = (“Adam”, “Bob”, “Chris”, “David”, “Eve”) >>> tuple_int = (30, 50, 12, 60, 23, 50) >>> tuple_bool = (True, True, False, True, False) >>> tuple_float = (2.51, 62.3, 61.6234, 52.31) >>> tuple_mixed = (“Apple”, 11, False, “Banana”, 5.23) >>> #We can print the tuple by using the print() function >>> print(tuple_int) (30, 50, 12, 60, 23, 50) Accessing Tuple Elements >>> grades = (97, 82, 76, 88, 79) >>> print(grades) 88 >>> print(grades[1:3]) (82, 76) >>> print(grades[::2]) (97,76,79) >>> print(grades[-1]) 79 Tuple are immutable. Changing element is not possible. >>> grades = (97, 82, 76, 88, 79) >>> grades = 99 Traceback (most recent call last): File “”, line1, in TypeError: ‘tuple’ object does not support item assignment >>> Unpacking tuple >>> grades = (97, 82, 76, 88, 79) >>> std1, std2, std3, std4, std5 = grades >>> print(std1) 97 >>> print(std4) 88 >>> print(std2) 82 Unpacking tuple with asterisk >>> colors = (“red”, “blue”, “green”, “yellow”) >>> color1, color2, *color3 = colors >>> print(color1) red >>> print(color2) blue >>> print(color3) [“green”, “yellow”] Unpacking tuple with asterisk >>> colors = (“red”, “blue”, “green”, “yellow”) >>> color1, *color2, color3 = colors >>> print(color1) red >>> print(color2) [“blue”, “green”] >>> print(color3) yellow Length of tuple >>> colors = (“red”, “blue”, “green”, “yellow”) >>> len(colors) 5 Checking Membership >>> colors = (“red”, “blue”, “green”, “yellow”) >>> “red” in colors True >>> “orange” in colors False >>> if “green” in colors:... print(“Found it in the tuple”)... Found it in the tuple >>> Looping Through a Tuple >>> grades = (97, 82, 76, 88, 79) >>> total = 0 >>> for grade in grades:... total += grade... print(total) 97 179 255 343 422 >>> Set Data Structures List Tuple Set Dictionary Ordered Ordered Unordere Ordered Mutable Immutabl d Mutable Square e Immutabl Curly Bracket [] Parenthe e Braces {} sis () Curly Key:Value Braces {} Pairs Unique Elements Creating a set >>> set_str = {“Adam”, “Bob”, “Chris”, “David”, “Eve”} >>> set_int = {30, 50, 12, 60, 23, 50} >>> set_bool = {True, True, False, True, False} >>> set_float = {2.51, 62.3, 61.6234, 52.31} >>> set_mixed = {“Apple”, 11, False, “Banana”, 5.23} >>> #We can print the list by using the print() function >>> print(set_mixed) {“Apple”, 11, False, “Banana”, 5.23} >>> Sets are unordered and immutable >>> my_set = {“Adam”, “Bob”, “Chris”, “David”, “Eve”} >>> print(my_set) {'David', 'Adam', 'Bob', 'Eve', 'Chris’} >>> my_set Traceback (most recent call last): File "", line 1, in TypeError: 'set' object is not subscriptable Duplicates are not allowed >>> my_set = {“Adam”, “Bob”, “Adam”, “Chris”, “Bob”} >>> print(my_set) {'Adam', 'Chris', 'Bob'} Inserting elements in the set.add(item) method used to add an element in a set..update(iterable) method used to add the elements of an iterable in a set. Inserting elements in the list >>> my_set = {“Apple”, “Banana”, “Cherry”} >>> my_set.add(“Mango”) >>> print(my_set) {“Apple”, “Cherry”, “Banana”, “Mango”} >>> my_tuple = (“Fish”, “Meat”) >>> my_set.update(my_tuple) >>> print(my_set) {“Meat”, “Cherry”, “Banana”, “Apple”, “Fish”, “Mango”} Removing elements in the set.remove(item) method used for removing a specified item in the set.pop() method used for removing the last item in the set. However, since set is unordered, we cannot know what item will be removed. It also returns the removed object..discard(item) mothod used for removing a specified item in the set, but will not raise an error if the item is not in the set. Removing elements in the set >>> card = {1h, 2c, 5d, 6s, 1c, 5d} >>> card.remove(5d) >>> print(card) {2c, 1c, 1h, 6s} >>> card.discard(7h) >>> print(card) {2c, 1c, 1h, 6s} >>> card.pop() 2c >>> print(card) {1c, 1h, 6s} Length of set >>> card = {1h, 2c, 5d, 6s, 1c, 5d} >>> len(card) 5 Looping Through a Set >>> brands = {“LV”, “CK”, “Gucci”, “Dior”, “Armani”} >>> for brand in brands:... print(f“This brand is called {brands}.”)... This brand is called CK. This brand is called Armani. This brand is called Gucci. This brand is called Dior. This brand is called LV. >>> Data Structures List Tuple Set Dictionary Ordered Ordered Unordere Ordered Mutable Immutabl d Mutable Square e Immutabl Curly Bracket [] Parenthe e Braces {} sis () Curly Key:Value Braces {} Pairs Unique Elements List comprehension Python’s shortcut for listing elements List Comprehension This is a syntax in python that offers a shorter syntax when you want to create a new list based on the values of an existing list or an iterable. List Comprehension >>> my_list = [0,1,2,3,4,5,6] >>> newlist = [] >>> for item in my_list:... if item % 2 == 0:... newlist.append(item)... >>> print(newlist) [0,2,4,6] List Comprehension >>> my_list = [0,1,2,3,4,5,6] >>> newlist = [item for item in my_list if item % 2 == 0] >>> print(newlist) [0,2,4,6] List Comprehension Syntax varName = [expression for item in iterable if condition == True] Assign the value of the expression to varName from the for loop of an iterable if the condition is True. Lab Activity Mean, Median, Mode Mean, Median, Mode Mean The average value of a given set of numbers. Median The middle value of a given data set arranged in ascending order. If the number of data is even, take the average of the two middle number. Mode The most frequently occurring value in a dataset. Mean, Median, Mode Considering the data set of: 47, 9, 76, 22, 55, 69, 87, 2, 42, 83, 68, 80, 49, 26, 68, 19, 96, 59, 2, 38, 71, 50, 13, 98, 68 Find the mean, median, mode