datastructures in python
TRANSCRIPT
Datastructures in Python
- Ram Sagar Mourya
Hyderabad Python User Group
Types of data structuresThere 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 typeWe 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 listEg: >> 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 xEg: >> 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 listEg: >> 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']
Practice1). 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 Dictionarydict.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
PracticeWrite a program to read the student and marks and make a dictionary Sample Input: Enter the details : Mahesh 20 Output: {‘Mahesh’ : 20 }
Practice2. 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,emailSample 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>> a2>> b1
>> a = 1>> b = 2>> a, b = b, a>> a2>> b1
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 pairURL : 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/
• FacebookURL : https://www.facebook.com/HydPy/
Connect