SlideShare a Scribd company logo
List and Dictionaries
Objectives
In this session, you will learn to use:
List.
Understanding List Operations and Methods.
Parsing Lines.
Implementing Objects, Values and Arguments.
Use Dictionaries Functions and Methods.
Differences between Lists and Dictionaries.
Most versatile datatype available in python.
Defined as a sequence of values.
Holds Homogenous set of items.
Indices start at 0.
Lists are Mutable.
Example:
List
>>>list1=[10,20,30,40]
>>>list2=['Harish','Suresh','Kunal','Girish’]
>>>list1=[17,119]
>>>list[1]=90
>>>print list1
[17,90]
Traversing means visiting all the elements in the list.
Traversing is required to Search, Update and Delete values
from List.
Traversing List
>>>dept=[‘IT',‘CSE',‘ECE',‘CSE']
>>>for d in dept
print (d)
IT
CSE
ECE
CSE
>>>numbers=[10,20,30,40]
>>>for i in range(len(numbers)):
numbers[i]=numbers[i]*2
print(numbers[i])
20
40
60
80
Output
Operators used in list
+ - used to concatenate the list.
* - used to repeat a list for a number of times.
: - used to check a range of characters.
List Operations & Slices
>>>a=[1,2,3]
>>>b=[4,5,6]
>>>c=a+b
>>>print(c)
Output : [1,2,3,4,5,6]
>>>a=[10,20,30]
>>>a*2
Output:
[10,20,30,10,20,30]
>>>
alpha=['a','b','c','d','e',
'f']
>>> alpha[1:3]
Output :['b', 'c‘]
Examples
The following methods are used in Python for manipulating the
list:
List Methods
Method Name Description
append() This method is used to add a new element to the end of a list.
extend() This method is used to take a list as an argument and appends all the
elements.
sort() This method is used to arrange the elements of the list from low to
high.
Example
>>> mylist=['A','B','C']
>>> mylist.append('D')
>>> print (mylist)
['A', 'B', 'C', 'D']
There are several ways to delete elements from a list.
Ways Description
pop() method It modifies the list and returns the element that was removed. If we
don't provide an index value then it deletes the last element and
returns the value.
del operator If we do not want to retain the value which we have deleted using an
index then we need to use the del operator.
remove() method If we know the element to be removed then we can use the remove()
method.
Example
>>> mylist1=['A','B','C']
>>> element=mylist1.pop(1)
>>> print(mylist1)
['A', 'C']
List Methods (Contd.)
There are a number of built in functions that can be used on lists.
Function Name Description
sum() Using this function we can add the elements of the list. It will work only with
the numbers.
min() Using this function we can find the minimum value from the list.
max() Using this function we can find the maximum value from the list
len() Using this function we can find the number of elements in the list.
Example
>>> numbers=[10,20,30,40,50]
>>> print(len(numbers))
5
>>> print(max(numbers))
50
List Functions
String Is a sequence of characters.
Methods in Strings
list() is used to convert a string to list of characters.
split() is used to break the string into list of words.
split() takes an optional argument called delimiter which specifies the
word boundaries.
String and Its
Methods
>>> str='I am studying in NIIT'
>>> t=str.split()
>>> print(t)
['I', 'am', 'studying', 'in', 'NIIT']
Parsing means, dividing a string into tokens based on some
delimiters.
It is used to find a particular word from a file or search a
pattern
Parsing of Lines
Example Code:
fhand = open(‘MyText.txt')
for line in fhand:
line = line.rstrip()
if not line.startswith('From ') :
continue
words = line.split()
print words[2]
Contents of MyText.txt
From stephen.marquard@uct.ac.za
Sat Jan 5 09:14:16 2008
Output:
Sat
Activity
Activity : Understanding Collection Operations
Problem Statement:
Write a menu based program to insert , remove, sort, extend, reverse and traverse a list of
items.
Hint: Define functions to perform different operation of list, such as insertList() and
removeList() etc.
In python every data is represented as an Object.
Example:
In the preceding example, obj1 and obj2 are pointing to the
same string hence they are identical.
Objects & Values
Example:
In the preceding example obj1 and obj2 are pointing to the
same values hence they are equivalent . But they are not
identical.
Objects & Values
(Contd.)
The association of a variable with an object is called a reference.
An object with more than one reference, has more than one name and is
called as aliasing.
Aliasing
List can be passed as an argument to a function.
Passing a list as an argument to a function gets the reference
of the list.
List Arguments
Just a Minute
_____ method is used to break the
string into list of words.
Just a Minute
_____ method is used to break
the string into list of words.
split
Answer:
Introduction to Dictionary
Dictionary
It is a “bag” of values, each with its own label.
It contains the values in the form of key-value pair.
Every value in Dictionary is associated with a key.
calculator
perfume
money
tissue
candy
Dictionaries are Python’s most powerful data collection.
Dictionaries allow us to do fast database-like operations in Python.
Dictionaries have different names in different languages.
Associative Arrays - Perl / PHP.
Properties or Map or HashMap – Java.
Property Bag - C# / . NET.
Dictionary Keys can be of any Python data type.
Because keys are used for indexing, they should be immutable.
Dictionary Values can be of any Python data type.
Values can be mutable or immutable.
Characteristics of
Dictionary
Creating a Dictionary
Dictionary literals use curly braces and have a list of key-value pairs.
You can make an empty dictionary using empty curly braces
Example of a Dictionary
Creating a Dictionary
(Contd.)
Lists index their entries based on the position in the list.
In general, the order of items in a dictionary is unpredictable.
Dictionaries are indexed by keys.
Example:
Methods of Dictionary
S.No Method Name Description
1
dict.clear() Removes all elements of the dictionary ”dict”
2
dict.copy() Returns a shallow copy of dictionary ”dict”
3
dict.fromkeys(seq[,value])
Returns a new dictionary with keys from a supplied seq and
values all set to specified value
4
dict.get(key, default=None)
Returns value of given key or returns default if key not in
dictionary.
5
dict.has_key(key)
Returns true if key in dictionary ”dict” false otherwise
6
dict.items() Returns a list of (key, value) tuple pairs from dictionary “dict”
7
dict.keys() Returns list of keys from dictionary “dict”
8
dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not
already in “dict”
9
dict.update(dict2) Adds dictionary ”dict2” key-values pairs to ”dict”
10
dict.values() Returns list of values from dictionary ”dict”.
Keys and Values
The keys() method returns a list of the keys in a dictionary.
The values() method returns a list of the values.
5/10/09 Python Mini-Course: Lesson 16 23
The items() method returns a list of tuple pairs of the key-value
pairs in a dictionary.
5/10/09 Python Mini-Course: Lesson 16 24
Keys and Values (Contd.)
To access dictionary elements, you can use the familiar square
brackets along with the key to obtain its value.
Example:
5/10/09 Python Mini-Course: Lesson 16 25
Keys and Values (Contd.)
Len() Function
The len() function works on dictionaries.
Len() returns the number of key-value pair.
Example:
5/10/09 Python Mini-Course: Lesson 16 26
“in” Operator
The “in” Operator works differently for dictionaries than for
other sequences as below
It tells whether data appears as a key in the dictionary.
It can be used to check whether a value exists in a dictionary.
values() method
It checks the values existing in a dictionary.
It will return the result as a List.
5/10/09 Python Mini-Course: Lesson 16 27
Example:
5/10/09 Python Mini-Course: Lesson 16 28
“in” Operator (Contd.)
“get()” Method for
Dictionary
The method get() returns a value for the given key.
If key is not available, it returns default value “None”.
key- This is the key to be searched in the dictionary.
default - This is the value to be returned in case key does not exist.
Example:
Traversing a Dictionary
We can write a “for” loop that goes through all the entries in a dictionary, such
as keys and values.
If a dictionary uses in a “for” statement, it traverses the keys of the dictionary.
This loop prints each key and the corresponding value.
Example:
Dictionary Traceback
It is an error to reference a key which is not in the dictionary.
We can use the “in” operator to see if a key is in the dictionary.
List vs Dictionary
LIST DICTIONARY
List is list of values. Starting from zero.
It is an index of words and each of them has a
definition.
We can add the element index wise.
Element can be added in Dictionary in the form
of key-value pair.
Just a Minute
Predict the output of the
following Code:
Data={‘Apple’,’Orange’,’Grapes’}
‘Apple’ in Data
Just a Minute
Predict the output of the
following Code:
Data={‘Apple’,’Orange’,’Grapes’}
‘Apple’ in Data
True
Answer:
Activity
Activity : Implementing Dictionary Collection
Problem Statement:
Write a program to create two dictionary objects named states and cities with the following
items:
States : Cities :
'Oregon': 'OR' 'CA': 'San Francisco'
'Florida': 'FL' 'MI': 'Detroit'
'California': 'CA' 'FL': 'Jacksonville'
'New York': 'NY'
'Michigan': 'MI'
In addition add more two items to the cities dictionary(NY-New York, OR-Portland). Then
print the details available in cities dictionary using keys and values.
Summary
 In this session we have learned:
 Parsing means dividing a string into tokens based on some delimiters.
 An object comprises both data members (class variables and instance
variables) and methods.
 An object with more than one reference has more than one name and
hence the object is said to be aliased.
 Creating a dictionary.
 Different methods in a dictionary.
 “in” operator for checking the keys existing in dictionary.
 Traversing through the Dictionary.
 Differences between List and Dictionary.

More Related Content

PDF
List , tuples, dictionaries and regular expressions in python
PPTX
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
PPTX
Python introduction data structures lists etc
PPTX
fundamental of python --- vivek singh shekawat
DOC
Revision Tour 1 and 2 complete.doc
PPTX
Python - List, Dictionaries, Tuples,Sets
PPTX
ITS-16163: Module 5 Using Lists and Dictionaries
PPTX
Datastructures in python
List , tuples, dictionaries and regular expressions in python
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
Python introduction data structures lists etc
fundamental of python --- vivek singh shekawat
Revision Tour 1 and 2 complete.doc
Python - List, Dictionaries, Tuples,Sets
ITS-16163: Module 5 Using Lists and Dictionaries
Datastructures in python

Similar to Python Dynamic Data type List & Dictionaries (20)

PPTX
Python Lecture 8
PPTX
Python PPT.pptx
PPTX
Dictionariesasdfghjsdfghjklsdfghjkl.pptx
PPTX
Chapter 3-Data structure in python programming.pptx
PPTX
Python chapter 2
PPTX
python chapter 1
PPT
ComandosDePython_ComponentesBasicosImpl.ppt
PDF
ESIT135 Problem Solving Using Python Notes of Unit-3
PDF
"Automata Basics and Python Applications"
PPTX
Chapter 16 Dictionaries
PPTX
List_tuple_dictionary.pptx
PPTX
Lists.pptx
PPTX
datastrubsbwbwbbwcturesinpython-3-4.pptx
PDF
Py4Inf-08-Lists ListsListsListsListsListsListsListsListsListsListsListsLists.pdf
PDF
Python elements list you can study .pdf
PPTX
Chapter 14 Dictionary.pptx
PPTX
DICTIONARIES (1).pptx
PPTX
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
PDF
Lecture-6.pdf
PPTX
Pa1 session 3_slides
Python Lecture 8
Python PPT.pptx
Dictionariesasdfghjsdfghjklsdfghjkl.pptx
Chapter 3-Data structure in python programming.pptx
Python chapter 2
python chapter 1
ComandosDePython_ComponentesBasicosImpl.ppt
ESIT135 Problem Solving Using Python Notes of Unit-3
"Automata Basics and Python Applications"
Chapter 16 Dictionaries
List_tuple_dictionary.pptx
Lists.pptx
datastrubsbwbwbbwcturesinpython-3-4.pptx
Py4Inf-08-Lists ListsListsListsListsListsListsListsListsListsListsListsLists.pdf
Python elements list you can study .pdf
Chapter 14 Dictionary.pptx
DICTIONARIES (1).pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
Lecture-6.pdf
Pa1 session 3_slides
Ad

More from RuchiNagar3 (6)

PDF
D34010.pdf
PPTX
PYTHON-VS-JAVA.pptx
PPTX
DATA-STRUCTURES.pptx
PPTX
INTRODUCTION-TO-PYTHON
PPTX
Web-Dev-Through-Python
PPTX
Html intro
D34010.pdf
PYTHON-VS-JAVA.pptx
DATA-STRUCTURES.pptx
INTRODUCTION-TO-PYTHON
Web-Dev-Through-Python
Html intro
Ad

Recently uploaded (20)

PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PPTX
Revamp in MTO Odoo 18 Inventory - Odoo Slides
PPTX
How to Manage Loyalty Points in Odoo 18 Sales
PDF
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
PPTX
An introduction to Dialogue writing.pptx
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
LDMMIA Reiki Yoga Workshop 15 MidTerm Review
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
PDF
High Ground Student Revision Booklet Preview
PDF
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
PPTX
IMMUNIZATION PROGRAMME pptx
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
PPTX
How to Manage Global Discount in Odoo 18 POS
PPTX
Strengthening open access through collaboration: building connections with OP...
PPTX
vedic maths in python:unleasing ancient wisdom with modern code
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
PDF
UTS Health Student Promotional Representative_Position Description.pdf
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Open Quiz Monsoon Mind Game Final Set.pptx
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
Revamp in MTO Odoo 18 Inventory - Odoo Slides
How to Manage Loyalty Points in Odoo 18 Sales
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
An introduction to Dialogue writing.pptx
Week 4 Term 3 Study Techniques revisited.pptx
LDMMIA Reiki Yoga Workshop 15 MidTerm Review
The Final Stretch: How to Release a Game and Not Die in the Process.
High Ground Student Revision Booklet Preview
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
IMMUNIZATION PROGRAMME pptx
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
How to Manage Global Discount in Odoo 18 POS
Strengthening open access through collaboration: building connections with OP...
vedic maths in python:unleasing ancient wisdom with modern code
NOI Hackathon - Summer Edition - GreenThumber.pptx
UTS Health Student Promotional Representative_Position Description.pdf

Python Dynamic Data type List & Dictionaries

  • 2. Objectives In this session, you will learn to use: List. Understanding List Operations and Methods. Parsing Lines. Implementing Objects, Values and Arguments. Use Dictionaries Functions and Methods. Differences between Lists and Dictionaries.
  • 3. Most versatile datatype available in python. Defined as a sequence of values. Holds Homogenous set of items. Indices start at 0. Lists are Mutable. Example: List >>>list1=[10,20,30,40] >>>list2=['Harish','Suresh','Kunal','Girish’] >>>list1=[17,119] >>>list[1]=90 >>>print list1 [17,90]
  • 4. Traversing means visiting all the elements in the list. Traversing is required to Search, Update and Delete values from List. Traversing List >>>dept=[‘IT',‘CSE',‘ECE',‘CSE'] >>>for d in dept print (d) IT CSE ECE CSE >>>numbers=[10,20,30,40] >>>for i in range(len(numbers)): numbers[i]=numbers[i]*2 print(numbers[i]) 20 40 60 80 Output
  • 5. Operators used in list + - used to concatenate the list. * - used to repeat a list for a number of times. : - used to check a range of characters. List Operations & Slices >>>a=[1,2,3] >>>b=[4,5,6] >>>c=a+b >>>print(c) Output : [1,2,3,4,5,6] >>>a=[10,20,30] >>>a*2 Output: [10,20,30,10,20,30] >>> alpha=['a','b','c','d','e', 'f'] >>> alpha[1:3] Output :['b', 'c‘] Examples
  • 6. The following methods are used in Python for manipulating the list: List Methods Method Name Description append() This method is used to add a new element to the end of a list. extend() This method is used to take a list as an argument and appends all the elements. sort() This method is used to arrange the elements of the list from low to high. Example >>> mylist=['A','B','C'] >>> mylist.append('D') >>> print (mylist) ['A', 'B', 'C', 'D']
  • 7. There are several ways to delete elements from a list. Ways Description pop() method It modifies the list and returns the element that was removed. If we don't provide an index value then it deletes the last element and returns the value. del operator If we do not want to retain the value which we have deleted using an index then we need to use the del operator. remove() method If we know the element to be removed then we can use the remove() method. Example >>> mylist1=['A','B','C'] >>> element=mylist1.pop(1) >>> print(mylist1) ['A', 'C'] List Methods (Contd.)
  • 8. There are a number of built in functions that can be used on lists. Function Name Description sum() Using this function we can add the elements of the list. It will work only with the numbers. min() Using this function we can find the minimum value from the list. max() Using this function we can find the maximum value from the list len() Using this function we can find the number of elements in the list. Example >>> numbers=[10,20,30,40,50] >>> print(len(numbers)) 5 >>> print(max(numbers)) 50 List Functions
  • 9. String Is a sequence of characters. Methods in Strings list() is used to convert a string to list of characters. split() is used to break the string into list of words. split() takes an optional argument called delimiter which specifies the word boundaries. String and Its Methods >>> str='I am studying in NIIT' >>> t=str.split() >>> print(t) ['I', 'am', 'studying', 'in', 'NIIT']
  • 10. Parsing means, dividing a string into tokens based on some delimiters. It is used to find a particular word from a file or search a pattern Parsing of Lines Example Code: fhand = open(‘MyText.txt') for line in fhand: line = line.rstrip() if not line.startswith('From ') : continue words = line.split() print words[2] Contents of MyText.txt From [email protected] Sat Jan 5 09:14:16 2008 Output: Sat
  • 11. Activity Activity : Understanding Collection Operations Problem Statement: Write a menu based program to insert , remove, sort, extend, reverse and traverse a list of items. Hint: Define functions to perform different operation of list, such as insertList() and removeList() etc.
  • 12. In python every data is represented as an Object. Example: In the preceding example, obj1 and obj2 are pointing to the same string hence they are identical. Objects & Values
  • 13. Example: In the preceding example obj1 and obj2 are pointing to the same values hence they are equivalent . But they are not identical. Objects & Values (Contd.)
  • 14. The association of a variable with an object is called a reference. An object with more than one reference, has more than one name and is called as aliasing. Aliasing
  • 15. List can be passed as an argument to a function. Passing a list as an argument to a function gets the reference of the list. List Arguments
  • 16. Just a Minute _____ method is used to break the string into list of words.
  • 17. Just a Minute _____ method is used to break the string into list of words. split Answer:
  • 18. Introduction to Dictionary Dictionary It is a “bag” of values, each with its own label. It contains the values in the form of key-value pair. Every value in Dictionary is associated with a key. calculator perfume money tissue candy
  • 19. Dictionaries are Python’s most powerful data collection. Dictionaries allow us to do fast database-like operations in Python. Dictionaries have different names in different languages. Associative Arrays - Perl / PHP. Properties or Map or HashMap – Java. Property Bag - C# / . NET. Dictionary Keys can be of any Python data type. Because keys are used for indexing, they should be immutable. Dictionary Values can be of any Python data type. Values can be mutable or immutable. Characteristics of Dictionary
  • 20. Creating a Dictionary Dictionary literals use curly braces and have a list of key-value pairs. You can make an empty dictionary using empty curly braces Example of a Dictionary
  • 21. Creating a Dictionary (Contd.) Lists index their entries based on the position in the list. In general, the order of items in a dictionary is unpredictable. Dictionaries are indexed by keys. Example:
  • 22. Methods of Dictionary S.No Method Name Description 1 dict.clear() Removes all elements of the dictionary ”dict” 2 dict.copy() Returns a shallow copy of dictionary ”dict” 3 dict.fromkeys(seq[,value]) Returns a new dictionary with keys from a supplied seq and values all set to specified value 4 dict.get(key, default=None) Returns value of given key or returns default if key not in dictionary. 5 dict.has_key(key) Returns true if key in dictionary ”dict” false otherwise 6 dict.items() Returns a list of (key, value) tuple pairs from dictionary “dict” 7 dict.keys() Returns list of keys from dictionary “dict” 8 dict.setdefault(key, default=None) Similar to get(), but will set dict[key]=default if key is not already in “dict” 9 dict.update(dict2) Adds dictionary ”dict2” key-values pairs to ”dict” 10 dict.values() Returns list of values from dictionary ”dict”.
  • 23. Keys and Values The keys() method returns a list of the keys in a dictionary. The values() method returns a list of the values. 5/10/09 Python Mini-Course: Lesson 16 23
  • 24. The items() method returns a list of tuple pairs of the key-value pairs in a dictionary. 5/10/09 Python Mini-Course: Lesson 16 24 Keys and Values (Contd.)
  • 25. To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Example: 5/10/09 Python Mini-Course: Lesson 16 25 Keys and Values (Contd.)
  • 26. Len() Function The len() function works on dictionaries. Len() returns the number of key-value pair. Example: 5/10/09 Python Mini-Course: Lesson 16 26
  • 27. “in” Operator The “in” Operator works differently for dictionaries than for other sequences as below It tells whether data appears as a key in the dictionary. It can be used to check whether a value exists in a dictionary. values() method It checks the values existing in a dictionary. It will return the result as a List. 5/10/09 Python Mini-Course: Lesson 16 27
  • 28. Example: 5/10/09 Python Mini-Course: Lesson 16 28 “in” Operator (Contd.)
  • 29. “get()” Method for Dictionary The method get() returns a value for the given key. If key is not available, it returns default value “None”. key- This is the key to be searched in the dictionary. default - This is the value to be returned in case key does not exist. Example:
  • 30. Traversing a Dictionary We can write a “for” loop that goes through all the entries in a dictionary, such as keys and values. If a dictionary uses in a “for” statement, it traverses the keys of the dictionary. This loop prints each key and the corresponding value. Example:
  • 31. Dictionary Traceback It is an error to reference a key which is not in the dictionary. We can use the “in” operator to see if a key is in the dictionary.
  • 32. List vs Dictionary LIST DICTIONARY List is list of values. Starting from zero. It is an index of words and each of them has a definition. We can add the element index wise. Element can be added in Dictionary in the form of key-value pair.
  • 33. Just a Minute Predict the output of the following Code: Data={‘Apple’,’Orange’,’Grapes’} ‘Apple’ in Data
  • 34. Just a Minute Predict the output of the following Code: Data={‘Apple’,’Orange’,’Grapes’} ‘Apple’ in Data True Answer:
  • 35. Activity Activity : Implementing Dictionary Collection Problem Statement: Write a program to create two dictionary objects named states and cities with the following items: States : Cities : 'Oregon': 'OR' 'CA': 'San Francisco' 'Florida': 'FL' 'MI': 'Detroit' 'California': 'CA' 'FL': 'Jacksonville' 'New York': 'NY' 'Michigan': 'MI' In addition add more two items to the cities dictionary(NY-New York, OR-Portland). Then print the details available in cities dictionary using keys and values.
  • 36. Summary  In this session we have learned:  Parsing means dividing a string into tokens based on some delimiters.  An object comprises both data members (class variables and instance variables) and methods.  An object with more than one reference has more than one name and hence the object is said to be aliased.  Creating a dictionary.  Different methods in a dictionary.  “in” operator for checking the keys existing in dictionary.  Traversing through the Dictionary.  Differences between List and Dictionary.

Editor's Notes

  • #2: In this session you will learn to introduction to list , understand the list operation and methods of list , parsing of the lines , object and values and list of arguments. You will also learn to use dictionary , function and methods of dictionary and also difference between lists and dictionaries.
  • #3: List is a most versatile datatype available in python. It is defined as a sequence of values. List contain values with comma separated between two square brackets. All the items of the list should be of the same type. List indices start at 0. There are several ways to create a new list. The simplest is to enclose the elements in square brackets. Example >>>list1=[10,20,30,40] >>>list2=['Harish','Suresh','Kunal','Girish] List that contains no elements is called an empty list. We can create an empty list using empty brackets []. Example >>>empty1=[] Here empty1 is the empty list which does not contain any elements. List are mutable because we can change the order of the items. We can reassign an element in a list.
  • #4: The common way to traverse the elements of a list with for loop.
  • #5: List respond to the "+" operator much like strings they mean concatenation. Example >>>a=[1,2,3] >>>b=[4,5,6] >>>c=a+b >>>print(c) [1,2,3,4,5,6] In the above example when list a and b has been added and stored in c. Then c has displayed the elements of a and b by concatenating. List respond to the "*" operator for repeats a list a given number of times. Example >>>a=[10,20,30] >>>a*4 [10,20,30,10,20,30,10,20,30,10,20,30] In the above example when list a is multiplied by 4 then the elements of list a is printed for four times. Slice operator also work on lists. Using this operator we can see certain range of characters also. >>> alpha=['a','b','c','d','e','f'] >>> alpha[1:3] ['b', 'c'] >>> alpha[:4] ['a', 'b', 'c', 'd'] >>> alpha[3:] ['d', 'e', 'f'] >>> alpha[:] ['a', 'b', 'c', 'd', 'e', 'f'] In the above example first alpha[1:3] will displayed the 1st index to until 3rd index. Then in the next alpha[:4] will show the elements from 0th index to until 4th index. Then in the next alpha[3:] will displayed last three elements of the list. And in alpha[:] will display whole list.
  • #6: Python provides methods that operate on lists. The following are some of the methods which are used for manipulating the list. append()- This method is used to add a new element to the end of a list. Example >>> mylist=['A','B','C'] >>> mylist.append('D') >>> print (mylist) ['A', 'B', 'C', 'D'] >>> extend() Method - This method is used to take a list as an argument and appends all the elements. Example >>> mylist1=['A','B','C'] >>> mylist2=['D','E'] >>> mylist1.extend(mylist2) >>> print(mylist1) ['A', 'B', 'C', 'D', 'E'] >>> sort() -This method is used to arrange the elements of the list from low to high. Example >>> mylist1=['D','C','E','B','A'] >>> mylist1.sort() >>> print(mylist1) ['A', 'B', 'C', 'D', 'E']
  • #7: There are several ways to delete elements from a list. Using pop() method - If we know the index of the element we want we can use pop(). Example >>> mylist1=['A','B','C'] >>> element=mylist1.pop(1) >>> print(mylist1) ['A', 'C'] >>> print(element) B >>> pop() modifies the list and returns the element that was removed. If we don't provide an index value then it deletes the last element and returns the value. Using del operator - If we do not want to retain the value which we have deleted using an index then we need to use del operator. Example >>> mylist1=['A','B','C'] >>> del mylist1[1] >>> print(mylist1) ['A', 'C'] >>> In the above example we have deleted the 1st index element i.e 'B' from the list. Using remove() method- If we know the element to be removed then we can use remove() method. Example >>> mylist1=['A','B','C'] >>> mylist1.remove('B') >>> print(mylist1) ['A', 'C'] In the above example we have used remove() method to remove the element 'B' from list.
  • #8: There are number of built in functions that can be used on lists that allow you to quickly look through a list without writing your own loops. The below is a small example of using these built in functions. Examples: >>> numbers=[10,20,30,40,50] >>> print(len(numbers)) 5 >>> print(max(numbers)) 50 >>> print(min(numbers)) 10 >>> print(sum(numbers)) 150 >>> print(sum(numbers)/len(numbers)) 30.0 >>> From these functions sum() function will work with only numbers. But other functions like max(),len(),min() etc will work with list of strings and other types that can be comparable
  • #9: A string is sequence of characters.A list is sequence of values of any type. list() method is used to convert a string to list of characters. Example >>> str='NIIT' >>> ele=list(str) >>> print ele ['N', 'I', 'I', 'T'] split() method is used to break the string into list of words Example >>> str='I am studying in NIIT' >>> t=str.split() >>> print(t) ['I', 'am', 'studying', 'in', 'NIIT'] split() method takes and optional argument called delimiter which specifies the word boundaries. A delimiter is a character which differentiate between one word to another in the below example the character "," is separating the words. Example >>> str='Harish,Sridhar,Kishore' >>> delimiter=',' >>> str.split(delimiter) ['Harish', 'Sridhar', 'Kishore'] join() method is the inverse of split. It takes a list of strings and concatenates the elements.join() is a string method. Example >>> str=['Delhi','Mumbai','Chennai','Kolkata'] >>> delimiter='-' >>> delimiter.join(str) 'Delhi-Mumbai-Chennai-Kolkata' In the above code str list contains four city names with comma separated. Using join() method it will.This method will be executed using a delimiter.
  • #10: Usually when we are reading a file we want to do something to the lines other than just printing the whole line. Often we want to find the a criteria based line and then parse the line to find some interesting part of the line. For example if we wanted to print out the day of the week from those lines that start with “From ”? From [email protected] Sat Jan 5 09:14:16 2008 The split method is very effective when faced with this kind of problem. We can write a small program that looks for lines where the line starts with “From ”, split those lines, and then print out the third word in the line: fhand = open(‘MyText.txt') for line in fhand: line = line.rstrip() if not line.startswith('From ') : continue words = line.split() print words[2] The program produces the following output: Sat
  • #11: Solution: In order to do this activity, you need to perform the following tasks: Create a Python empty project. Use while() to create the menu. Use append(), remove(), extend(), sort(), reverse() to perform list operation. Task 1: Create a Python empty project: Step 1: Open NetBeans 8.0.2. Step 2: Click File menu. Step 3: Select New Project. Step 4: Select Python from Categories list and Python Project from Projects list. Step 5: Click Next button. Step 6: On New Python Project dialog box set the Project Name as CR_Session08_Activity02. Step 7: Select project Location by clicking Browse button. Step 8: Click Finish button. Task 2: Use while() to create the menu, use append(), remove(), extend(), sort(), reverse() to perform list operation: Step 1: Type the following code: def insertList(nameList): item=raw_input("Enter an item to the list: ") nameList.append(item) def removeList(nameList): item=raw_input("Enter an item you want to remove from the list: ") nameList.remove(item) def sortList(nameList): nameList.sort() def showList(nameList): for item in nameList: print(item) def extendList(nameList): nameList1=[23,34,35] nameList.extend(nameList1) def reverseList(nameList): nameList.reverse() def quitList(): exit() nameList=[] while("true"): print("1. Insert an item into List.") print("2. Remove an item from List.") print("3. Sort items of List.") print("4. Extend List.") print("5. Reverse List.") print("6. Display items from List.") print("7. Quit.") numC=raw_input("Enter your option: ") num=int(numC) if(num==1): insertList(nameList) elif(num==2): removeList(nameList) elif(num==3): sortList(nameList) elif(num==4): extendList(nameList) elif(num==5): reverseList(nameList) elif(num==6): showList(nameList) elif(num==7): quit() Step 2: Run the program.
  • #12: We know that obj1 and obj2 both refer to a string, but we don't know whether they refer to the same string. To check whether two variables refer to the same object we need to use is operator. To check whether two variables refer to the same object, we can use the is operator. In the above program we have used the same and we received the output as True. Hence both the objects are pointing to the same string so they are identical
  • #13: In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical. Until now, we have been using “object” and “value” interchangeably, but it is more precise to say that an object has a value. If you execute obj1 = [10,20,30], obj1 refers to a list object whose value is a particular sequence of elements. If another list has the same elements, we would say it has the same value.
  • #14: Aliased object is mutable then changes made with one alias affect the other. This behavior can be useful at the same time error-prone. It is safer to avoid aliasing when we are working with mutable object. String is an immutable object where aliasing is not a problem.
  • #15: When you pass a list to a function, the function gets a reference to the list. If the function modifies a list parameter, the caller sees the change. In the above example, delete_head() method removes the first element from a list. The parameter val and the variable mylist are aliases for the same object.
  • #16: Solution: Split
  • #17: Solution: Split
  • #18: A dictionary is like a list, but more general. In a list, the index positions have to be integer but in a dictionary, the indices can be (almost) any type. We can think of a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each key maps to a value. The association of a key and a value is called a key-value pair or sometimes an item. The function dict() creates a new dictionary with no items. Because dict() is the name of a built-in function, we should avoid using it as a variable name.
  • #20: The curly brackets, {}, represent an empty dictionary. To add items to the dictionary, we can use square brackets. In the above program we have “jjj” variable is a dictionary which is having 3 values. And “ooo” variable does not have any values and hence an empty dictionary
  • #21: The function dict creates a new dictionary with no items. Because dict is the name of a built-in function, you should avoid using it as a variable name. >>>eng2sp=dict() >>>print eng2sp The curly brackets, {}, represent an empty dictionary. To add items to the dictionary, you can use square brackets: >>>eng2sp['one']='uno' This line creates an item that maps from the key ’one’ to the value 'uno'. If we print the dictionary again, we see a key-value pair with a colon between the key and value: >>>print eng2sp {'one':'uno'} This output format is also an input format. For example, you can create a new dictionary with three items: >>>eng2sp={'one':'uno','two':'dos','three':'tres'} When we print the may be the following output >>>print eng2sp {'one':'uno','three':'tres','two':'dos'} The order of the key-value pairs is not the same. If we type the same example on another computer we might get other results. So in general the order of items of dictionary is unpredictable.
  • #22: The above slide shows the different methods for working with dictionary. Example copy() Method The following example shows the usage of copy() method. >>>dict1={'Name':'Harish','Age':29} >>>dict2=dict1.copy() >>>print('New Dictionary:',str(dict2)) The output will be displayed like the following New Dictionary: {'Age':29,'Name':'Harish'}
  • #23: Properties of Dictionary Keys Dictionary values have no restrictions. They can be any arbitrary python object either standard objects or user-defined objects. There are two important points to remember about dictionary keys. 1.More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment. 2.Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. keys() method - This method keys() returns a list of all the available keys in the dictionary. values() method - The method values() returns a list of all the values available in a given dictionary.
  • #24: items() method The method items() returns a list of dicts (key,value) tuple pairs. The above program will display the key and value pair of the dictionary.
  • #25: The above is a sample example to access a particular element of dictionary using a key.
  • #26: In the above example it has shown len() function uses. This function will work on dictionaries. This will return the number of key and value pair. There is a snippet of code which displays the same.
  • #27: The in operator works differently for dictionaries than for other sequences. The in operator works on dictionaries. It tells whether something appears as a key in the dictionary. The in operator can be used to check whether a value existing in dictionary. To check the values existing in a dictionary we need use values() method. The values() method will return as a List.
  • #28: The above example explaining how in operator works on dictionary. Here the in operator is used to check whether a particular key or value exist in the dictionary or not. In operator will return true or false value.
  • #29: Get() Method The method get() returns a value for the given key. If key is not available then returns default value None. Syntax : dict.get(key,default=None) The parameter explained in below. key -This is the Key to be searched in the dictionary. default -This is the Value to be returned in case key does not exist. The above snippet of code displays the values by giving the key value using get() method.
  • #30: Even though dictionaries are not stored in order, we can write a for loop that goes through all the entries in a dictionary - actually it goes through all of the keys in the dictionary and looks up the values. If a dictionary uses in a for statement, it traverses the keys of the dictionary. In the above code snippet the for loop prints each key and the corresponding value.
  • #31: It is an error to reference a key which is not in the dictionary. We can use the in operator to see if a key is in the dictionary. The above examples show how an error comes when we are trying to print a value based on key value which is not existing in a empty dictionary.
  • #32: The above slide shows the difference between the list and dictionary. The slides shows the two snippet of code which show the difference between the list and dictionary. The snippet of code shows how to add elements to the list and dictionary and display it. The snippet code also shows how to access a particular element of a list or dictionary.
  • #33: Solution: True
  • #34: Solution: True
  • #35: Solution: In order to do this activity, you need to perform the following tasks: Create a Python empty project. Create a mapping of state to abbreviation, Create a basic set of states and some cities in them and Add some more cities. Task 1: Create a Python empty project: Step 1: Open NetBeans 8.0.2. Step 2: Click File menu. Step 3: Select New Project. Step 4: Select Python from Categories list and Python Project from Projects list. Step 5: Click Next button. Step 6: On New Python Project dialog box set the Project Name as CR_Session10_Exercise01. Step 7: Select project Location by clicking Browse button. Step 8: Click Finish button. Task 2: Create a mapping of state to abbreviation, create a basic set of states and some cities in them, add some more cities: Step 1: Type the following code: # create a mapping of state to abbreviation states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' } # create a basic set of states and some cities in them cities = { 'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville' } # add some more cities cities['NY'] = 'New York' cities['OR'] = 'Portland' # print out some cities print '-' * 10 print "NY State has: ", cities['NY'] print "OR State has: ", cities['OR'] # print some states print '-' * 10 print "Michigan's abbreviation is: ", states['Michigan'] print "Florida's abbreviation is: ", states['Florida'] # do it by using the state then cities dict print '-' * 10 print "Michigan has: ", cities[states['Michigan']] print "Florida has: ", cities[states['Florida']] # print every state abbreviation print '-' * 10 for state, abbrev in states.items(): print "%s is abbreviated %s" % (state, abbrev) # print every city in state print '-' * 10 for abbrev, city in cities.items(): print "%s has the city %s" % (abbrev, city) Step 2: Run the program.