Datastructures in Python - Ram Sagar Mourya Hyderabad Python User Group
Types of data structures There two types of data structures: • Built-in data structures, data structures that provided by default Eg: list, dictionary ,tuple… • User-defined data structures (classes in object oriented programming) that are designed for a particular task Eg: Stack , Queue…
Python built in data structures • Python has set of built in data structures : – lists – tuples – dictionaries – sets
Lists • An ordered collection of items • List items does not need to be of same type We can have numbers, strings , list etc in the same list • List notation • A = [1,”This is a list”, ‘c’,2.5] • B = [] • C = list()
Create a List
• Make a list using string >>> lst = 'Welcome to meetup'.split() >>> lst ['Welcome', 'to', 'meetup'] >>> lst = 'What,a,wonderful,world'.split(',') >>> lst ['What', 'a', 'wonderful', 'world']
• Access the items in the list >> names = [ ‘Rahul’, ‘Mahesh, ‘Aishwarya’ ] • Read one : >> names[0] >> Rahul >> names[-1] >> Aishwarya • Read one at a time : >> for name in names: print name Rahul Mahesh Aishwarya
Methods of Lists • List.append(x) – Adds an item to the end of the list Eg: >> list_items = [1, 2, 3, 4, 5] >> list_items.append(6) >> list_items >> [ 1, 2, 3, 4, 5, 6 ]
• List.extend(L) - Extends the list by appending all the items in the given list ‘L’ to the existing list Eg: >> list_items = [1, 2, 3, 4, 5] >> list_items.extend([6, 7, 8, 9]) >> list_items >> [ 1, 2, 3, 4, 5, 6, 7, 8 , 9 ]
• List.insert(i,x) - Inserts an item x at index i Eg: >> list_items = [1, 2, 3, 4, 5] >> list_items.insert(3, 10) >> list_items >> [ 1, 2, 3, 10, 4, 5]
• List.remove(x) - Removes the first occurrence of the item from the list whose value is x Eg: >> list_items = [1, 5, 3, 4, 5, 5] >> list_items.remove(5) >> list_items >> [ 1, 3, 4, 5, 5]
• List.pop(i) - Remove and returns item at index i,default value of i is last index of the list Eg: >> list_items = [1, 5, 3, 4, 5, 8] >> list_items.pop() >> 8 >> lst >> [1, 5, 3, 4, 5] >> list_items.pop(2) >> 3 >> lst [1, 5, 4, 5]
Some other methods of Lists • >> a = [1, 2, 3, 4, 5, 6, 7, 6] • a.count(x) # Returns occurrence of specified x >> a.count(6) >> 2 • a.index(x) # Returns the first index where the given value appears >> a.index(6) >> 5 • a.reverse() # Reverses order of list >> a.reverse() >> [6, 7, 6, 5, 4, 3, 2, 1] • a.sort() >> a >> [1, 2, 3, 4, 5, 6, 6, 7]
Slicing a List • List[ start, stop] >> lst = list(‘Monty Python’) >> lst >> ['M', 'o', 'n', 't', 'y', ' ', 'P', 'y', 't', 'h', 'o', 'n'] >> lst[6:10] >> ['P', 'y', 't', 'h'] >> lst[0 : 5] >> ['M', 'o', 'n', 't', 'y']
>> lst[6: 10] >> [''P', 'y', 't', 'h', 'o'] >> lst[-12 : -7] >> ['M', 'o', 'n', 't', 'y'] >> lst[:5] >> ['M', 'o', 'n', 't', 'y'] >> lst[5:] >> [' ', 'P', 'y', 't', 'h', 'o', 'n']
Practice 1). Write a program to read the input and process it Input will be items separated by space. Perform the following actions. a). Make a list of the input provided and print it b). Count the no of items in the list and print it c). Ask the user to provide a item as input and find the index of the item , if the item is not present print ‘Item not found’ else print the index. Find the Occurrence of the item in the list d). Reverse the list and print it e). Sort the list in descending order and print the sorted list Input : Enter the numbers :a c d e z k m o
Practice
Dictionary • Consists of Key– Value pair • Keys needs to unique • Items of the dictionary are not ordered Eg: >> empty_dict = dict() >> empty_dict >> {} >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> phonebook >> {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> Phonebook['Rock‘] >> 999999999
Modifying a Dictionary >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> phonebook['Rock‘] = 666666666 >> phonebook >> {'Rock': 666666666, 'Rashmi': 888888888, 'Mohan': 777777777} >> phonebook['Ricky'] = 3333333333 >> phonebook >> {'Rock': 999999999, 'Ricky': 3333333333, 'Rashmi': 888888888, 'Mohan': 777777777}
Methods in Dictionary dict.keys() >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> phonebook.keys() >> ['Mohan', 'Rashmi', 'Rock'] dict.values() >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> phonebook.values() >> [777777777, 888888888, 999999999]
• dict.items() >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> phonebook.items() >> [('Mohan', 777777777), ('Rashmi', 888888888), ('Rock', 999999999)]
dict.clear() >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> phonebook.clear() >> phonebook >> {}
dict.copy() >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> newPhoneBook = phonebook.copy() >> newPhoneBook >>{'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777}
• dict.get(key) >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> phonebook['Akshay'] >> phonebook.get('Mohan')
• in keyword : > >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> ‘Akshay’ in phonebook >> False >> ‘Rock’ in phonebook >> True
Practice Write a program to read the student and marks and make a dictionary Sample Input: Enter the details : Mahesh 20 Output: {‘Mahesh’ : 20 }
Practice 2. Write a program to read the names from the user and make a list of names , then loop through the list of name and ask for email. Make a dictionary of name,email Sample Input : Output:
Tuples • A tuple is a sequence of immutable Python objects. • Tuples are sequences, just like lists. • Any constant data that won’t change , better to use tuple >> tup1 = () >> tup2 = ('physics', 'chemistry', 1997, 2000) >> tup3 = (1, 2, 3, 4, 5 ) >> tup4 = "a", "b", "c", "d"
Accessing items in Tuple • Item can be access using the index >> languages = ('Hindi','English','Telugu','Gujarati','Marathi') >> languages[0] >> 'Hindi' • Slicing can be used in Tuple >> languages[0:3] ('Hindi', 'English', 'Telugu')
Simple example of Tuple • Swapping of numbers: >> a= 1 >> b = 2 >> temp = a >> a = b >> b = temp >> a 2 >> b 1 >> a = 1 >> b = 2 >> a, b = b, a >> a 2 >> b 1
Set • Sets are unordered collections of simple objects • Unique collections of immutable objects • Define a Set: >> set1 = set() >> set2 = {'Ramesh','Mahes','Suresh'} >> country = set(['India','America','Africa']) >> country >> set(['Africa', 'America', 'India', 'China'])
Methods in Set • Set.add(element) >> set2 = {'Ramesh','Mahes','Suresh'} >> set2.add('Himesh') >> set2 >> set(['Himesh', 'Ramesh', 'Suresh', 'Mahes'])
• copy >> names = {'Ramesh','Mahesh','Suresh'} >> new_names = names.copy() >> new_names >> set(['Mahesh', 'Ramesh', 'Suresh'])
• clear >> names = {'Ramesh','Mahesh','Suresh'} >> names.clear() >> names >> set([])
• difference >> x = {"a","b","c","d","e"} >> y = {"b","c"} >> x.difference(y) >> set(['a', 'e', 'd'])
• discard(ele) >> x = {"a","b","c","d","e"} >> x.discard("b") >> x >> set(['a', ‘c', 'e', 'd'])
• remove(ele) >> x = {"a","b","c","d","e"} >> x.remove("b") >> x >> set(['a', ‘c', 'e', 'd'])
• intersection >> x = {"a","b","c"} >> y = {"d","e"} >> x.intersection(y) >> set([]) >> y.add("b") >> x.intersection(y) >> set(["b"])
• union >> x = {"a","b","c"} >> y = {"d","e"} >> x.union(y)
• issubset >>> x = {"a","b","c"} >>> y = {"d","e"} >>> z = {"b","c"} >>> y.issubset(x) False >>> z.issubset(x) True
• issuperset >>> x = {"a","b","c","d"} >>> y = {"c", "d"} >>> x.issuperset(y) True >>> y.issuperset(x) False
• pop() • Remove and return an arbitrary set element. >>> x = {"a","b","c","d"} >>> x.pop() >>> ‘a’
Questions ?
• Sample text file for list operations: URL : http://bit.ly/2bnUBje Using this text file to make a list of words, and find the no.of words in the file, make a ‘Set’ of words (which will be a set of unique words). Find the no.of unique words. Make a dictionary of word – count , i.e word as key and count as value. • Sample text file with name,email pair URL : http://bit.ly/2bNGBPD Read this text file it contains , name and email . Read this text make a list and Then make a dictionary with name – email as key – value.
• Subscribe Mailing List: URL : https://mail.python.org/mm3/mailman3/lists/hydpy.python.org/ • Meetup page: URL : https://www.meetup.com/Hyderabad-Python-Meetup-Group/ • Facebook URL : https://www.facebook.com/HydPy/ Connect

Datastructures in python

  • 1.
    Datastructures in Python -Ram Sagar Mourya Hyderabad Python User Group
  • 2.
    Types of datastructures There two types of data structures: • Built-in data structures, data structures that provided by default Eg: list, dictionary ,tuple… • User-defined data structures (classes in object oriented programming) that are designed for a particular task Eg: Stack , Queue…
  • 3.
    Python built indata structures • Python has set of built in data structures : – lists – tuples – dictionaries – sets
  • 4.
    Lists • An orderedcollection of items • List items does not need to be of same type We can have numbers, strings , list etc in the same list • List notation • A = [1,”This is a list”, ‘c’,2.5] • B = [] • C = list()
  • 5.
  • 6.
    • Make alist using string >>> lst = 'Welcome to meetup'.split() >>> lst ['Welcome', 'to', 'meetup'] >>> lst = 'What,a,wonderful,world'.split(',') >>> lst ['What', 'a', 'wonderful', 'world']
  • 7.
    • Access theitems in the list >> names = [ ‘Rahul’, ‘Mahesh, ‘Aishwarya’ ] • Read one : >> names[0] >> Rahul >> names[-1] >> Aishwarya • Read one at a time : >> for name in names: print name Rahul Mahesh Aishwarya
  • 8.
    Methods of Lists •List.append(x) – Adds an item to the end of the list Eg: >> list_items = [1, 2, 3, 4, 5] >> list_items.append(6) >> list_items >> [ 1, 2, 3, 4, 5, 6 ]
  • 9.
    • List.extend(L) - Extendsthe list by appending all the items in the given list ‘L’ to the existing list Eg: >> list_items = [1, 2, 3, 4, 5] >> list_items.extend([6, 7, 8, 9]) >> list_items >> [ 1, 2, 3, 4, 5, 6, 7, 8 , 9 ]
  • 10.
    • List.insert(i,x) - Insertsan item x at index i Eg: >> list_items = [1, 2, 3, 4, 5] >> list_items.insert(3, 10) >> list_items >> [ 1, 2, 3, 10, 4, 5]
  • 11.
    • List.remove(x) - Removesthe first occurrence of the item from the list whose value is x Eg: >> list_items = [1, 5, 3, 4, 5, 5] >> list_items.remove(5) >> list_items >> [ 1, 3, 4, 5, 5]
  • 12.
    • List.pop(i) - Removeand returns item at index i,default value of i is last index of the list Eg: >> list_items = [1, 5, 3, 4, 5, 8] >> list_items.pop() >> 8 >> lst >> [1, 5, 3, 4, 5] >> list_items.pop(2) >> 3 >> lst [1, 5, 4, 5]
  • 13.
    Some other methodsof Lists • >> a = [1, 2, 3, 4, 5, 6, 7, 6] • a.count(x) # Returns occurrence of specified x >> a.count(6) >> 2 • a.index(x) # Returns the first index where the given value appears >> a.index(6) >> 5 • a.reverse() # Reverses order of list >> a.reverse() >> [6, 7, 6, 5, 4, 3, 2, 1] • a.sort() >> a >> [1, 2, 3, 4, 5, 6, 6, 7]
  • 14.
    Slicing a List •List[ start, stop] >> lst = list(‘Monty Python’) >> lst >> ['M', 'o', 'n', 't', 'y', ' ', 'P', 'y', 't', 'h', 'o', 'n'] >> lst[6:10] >> ['P', 'y', 't', 'h'] >> lst[0 : 5] >> ['M', 'o', 'n', 't', 'y']
  • 15.
    >> lst[6: 10] >>[''P', 'y', 't', 'h', 'o'] >> lst[-12 : -7] >> ['M', 'o', 'n', 't', 'y'] >> lst[:5] >> ['M', 'o', 'n', 't', 'y'] >> lst[5:] >> [' ', 'P', 'y', 't', 'h', 'o', 'n']
  • 16.
    Practice 1). Write aprogram to read the input and process it Input will be items separated by space. Perform the following actions. a). Make a list of the input provided and print it b). Count the no of items in the list and print it c). Ask the user to provide a item as input and find the index of the item , if the item is not present print ‘Item not found’ else print the index. Find the Occurrence of the item in the list d). Reverse the list and print it e). Sort the list in descending order and print the sorted list Input : Enter the numbers :a c d e z k m o
  • 17.
  • 18.
    Dictionary • Consists ofKey– Value pair • Keys needs to unique • Items of the dictionary are not ordered Eg: >> empty_dict = dict() >> empty_dict >> {} >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> phonebook >> {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> Phonebook['Rock‘] >> 999999999
  • 19.
    Modifying a Dictionary >>phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> phonebook['Rock‘] = 666666666 >> phonebook >> {'Rock': 666666666, 'Rashmi': 888888888, 'Mohan': 777777777} >> phonebook['Ricky'] = 3333333333 >> phonebook >> {'Rock': 999999999, 'Ricky': 3333333333, 'Rashmi': 888888888, 'Mohan': 777777777}
  • 20.
    Methods in Dictionary dict.keys() >>phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> phonebook.keys() >> ['Mohan', 'Rashmi', 'Rock'] dict.values() >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> phonebook.values() >> [777777777, 888888888, 999999999]
  • 21.
    • dict.items() >> phonebook= {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> phonebook.items() >> [('Mohan', 777777777), ('Rashmi', 888888888), ('Rock', 999999999)]
  • 22.
    dict.clear() >> phonebook ={'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> phonebook.clear() >> phonebook >> {}
  • 23.
    dict.copy() >> phonebook ={'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> newPhoneBook = phonebook.copy() >> newPhoneBook >>{'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777}
  • 24.
    • dict.get(key) >> phonebook= {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> phonebook['Akshay'] >> phonebook.get('Mohan')
  • 25.
    • in keyword: > >> phonebook = {'Rock': 999999999, 'Rashmi': 888888888, 'Mohan': 777777777} >> ‘Akshay’ in phonebook >> False >> ‘Rock’ in phonebook >> True
  • 26.
    Practice Write a programto read the student and marks and make a dictionary Sample Input: Enter the details : Mahesh 20 Output: {‘Mahesh’ : 20 }
  • 27.
    Practice 2. Write aprogram to read the names from the user and make a list of names , then loop through the list of name and ask for email. Make a dictionary of name,email Sample Input : Output:
  • 28.
    Tuples • A tupleis a sequence of immutable Python objects. • Tuples are sequences, just like lists. • Any constant data that won’t change , better to use tuple >> tup1 = () >> tup2 = ('physics', 'chemistry', 1997, 2000) >> tup3 = (1, 2, 3, 4, 5 ) >> tup4 = "a", "b", "c", "d"
  • 29.
    Accessing items inTuple • Item can be access using the index >> languages = ('Hindi','English','Telugu','Gujarati','Marathi') >> languages[0] >> 'Hindi' • Slicing can be used in Tuple >> languages[0:3] ('Hindi', 'English', 'Telugu')
  • 30.
    Simple example ofTuple • Swapping of numbers: >> a= 1 >> b = 2 >> temp = a >> a = b >> b = temp >> a 2 >> b 1 >> a = 1 >> b = 2 >> a, b = b, a >> a 2 >> b 1
  • 31.
    Set • Sets areunordered collections of simple objects • Unique collections of immutable objects • Define a Set: >> set1 = set() >> set2 = {'Ramesh','Mahes','Suresh'} >> country = set(['India','America','Africa']) >> country >> set(['Africa', 'America', 'India', 'China'])
  • 32.
    Methods in Set •Set.add(element) >> set2 = {'Ramesh','Mahes','Suresh'} >> set2.add('Himesh') >> set2 >> set(['Himesh', 'Ramesh', 'Suresh', 'Mahes'])
  • 33.
    • copy >> names= {'Ramesh','Mahesh','Suresh'} >> new_names = names.copy() >> new_names >> set(['Mahesh', 'Ramesh', 'Suresh'])
  • 34.
    • clear >> names= {'Ramesh','Mahesh','Suresh'} >> names.clear() >> names >> set([])
  • 35.
    • difference >> x= {"a","b","c","d","e"} >> y = {"b","c"} >> x.difference(y) >> set(['a', 'e', 'd'])
  • 36.
    • discard(ele) >> x= {"a","b","c","d","e"} >> x.discard("b") >> x >> set(['a', ‘c', 'e', 'd'])
  • 37.
    • remove(ele) >> x= {"a","b","c","d","e"} >> x.remove("b") >> x >> set(['a', ‘c', 'e', 'd'])
  • 38.
    • intersection >> x= {"a","b","c"} >> y = {"d","e"} >> x.intersection(y) >> set([]) >> y.add("b") >> x.intersection(y) >> set(["b"])
  • 39.
    • union >> x= {"a","b","c"} >> y = {"d","e"} >> x.union(y)
  • 40.
    • issubset >>> x= {"a","b","c"} >>> y = {"d","e"} >>> z = {"b","c"} >>> y.issubset(x) False >>> z.issubset(x) True
  • 41.
    • issuperset >>> x= {"a","b","c","d"} >>> y = {"c", "d"} >>> x.issuperset(y) True >>> y.issuperset(x) False
  • 42.
    • pop() • Removeand return an arbitrary set element. >>> x = {"a","b","c","d"} >>> x.pop() >>> ‘a’
  • 43.
  • 44.
    • Sample textfile for list operations: URL : http://bit.ly/2bnUBje Using this text file to make a list of words, and find the no.of words in the file, make a ‘Set’ of words (which will be a set of unique words). Find the no.of unique words. Make a dictionary of word – count , i.e word as key and count as value. • Sample text file with name,email pair URL : http://bit.ly/2bNGBPD Read this text file it contains , name and email . Read this text make a list and Then make a dictionary with name – email as key – value.
  • 45.
    • Subscribe MailingList: URL : https://mail.python.org/mm3/mailman3/lists/hydpy.python.org/ • Meetup page: URL : https://www.meetup.com/Hyderabad-Python-Meetup-Group/ • Facebook URL : https://www.facebook.com/HydPy/ Connect

Editor's Notes

  • #5 A List is nothing but a collection of items separated by commas in a square bracket. List can contain any type of data , i.e integers , string , float or even a list.
  • #6 To Create a list we just need to specify the items we want to have. The List class has two constructors, List() , List (iterable) List() -- > Used to create a empty list List(iterable) -- > Used to create a list out of the items in the iterable Here a iterable can be a string , tuple , dictionary , list or any other iterable
  • #8 To Create a list we just need to specify the items we want to have. The List class has two constructors, List() , List (iterable) List() -- > Used to create a empty list List(iterable) -- > Used to create a list out of the items in the iterable Here a iterable can be a string , tuple , dictionary , list or any other iterable
  • #9 Methods of Lists List.append(x) It add the item x to the end of the list
  • #10 List.extend(L): Extends the list by appending the items in the List ‘L’ to the existing list
  • #12 list.remove(x) : Removes the first occurrence of the item x from the list
  • #13 list.remove(x) : Removes the first occurrence of the item x from the list
  • #14 list.count() : It counts the number of times the specified item present in the list list.index() : It returns the first occurrence index of the specified item list.reverse() : Reverese the order of the list list.sort() : Sorts the list , default is ascending sort To get the list sorted in descending order , we can use list.sort(reverse=True)