Python Session 08j Updated
Python Session 08j Updated
Objectives
List.
Understanding List Operations and Methods.
Parsing Lines.
Implementing Objects, Values and Arguments.
Use Dictionaries Functions and Methods.
Differences between Lists and Dictionaries.
List
Example:
>>>list1=[17,119]
>>>list1=[10,20,30,40] >>>list[1]=90
>>>list2=['Harish','Suresh','Kunal','Girish’] >>>print list1
[17,90]
Traversing List
IT
CSE
ECE Output 20
CSE 40
60
80
List Operations &
Slices
Examples
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)
List Methods
(Contd.)
Example
>>> mylist1=['A','B','C']
>>> element=mylist1.pop(1)
>>> print(mylist1)
['A', 'C']
List Functions
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))
String and Its
Methods
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.
str = 'I am studying in NIIT'
t = str.split()
print(t)
Parsing of Lines
Hint: Define functions to perform different operation of list, such as insertList() and
removeList() etc.
Objects & Values
Example:
Answer: split
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.
tissue
candy
perfume
calculator
money
Characteristics of
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.)
Example:
Example:
values() method
Example:
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
LIST DICTIONARY
It is an index of words and each of them has a
List is list of values. Starting from zero. definition.
Element can be added in Dictionary in the form
We can add the element index wise. of key-value pair.
Just a Minute
Data={‘Apple’,’Orange’,’Grapes’}
‘Apple’ in Data
Just a Minute
Data={‘Apple’,’Orange’,’Grapes’}
‘Apple’ in Data
Answer: True
Activity