1 of 112

Working with List and Dictionary

Krishan Meena

JAWAHAR NAVODAYA VIDYALAYA PUDUCHERRY

2 of 112

LIST

  • They are container used to store any type of values.
  • They are mutable (it mean you can change the element of list).
  • A list can be created using square brackets.
  • Each element separated by comma.

[ ]

,

3 of 112

List samples

  • A=[2,4,6,8] list with int members
  • A=[] list with no members
  • A=[‘k’,’l’,’m’,’n’] list with string members
  • A=[1.2,2.2,3.2,4.20] list with float members
  • A=[‘a’,2,3.0,’kris’] list with mixed values memebers

4 of 112

Types of list

  • 1. Empty list
  • A=[]
  • Or
  • A=list()

5 of 112

Types of list

  • 2. long list
  • Contain many element
  • A=[1,2,5,6,8,9,10,22,56,89,98,96,56,2111,323,56,4879,2,3,6,79,56,8956,12]

6 of 112

Types of list

  • 3. nested list
  • If a list element have itself list called nested list.
  • A=[3,4,[5,6,7],8,9]
  • Here the list length is only 5 but it containing 7 element because the[5,6] is treated as one element only.

7 of 112

Creating list from existing sequence

  • We can use the following syntax to create the list from existing sequence:
  • Variable name=list(sequence)
  • A=list(‘hello’)
  • It work only with string values not with integer.

8 of 112

Creating list from existing sequence

9 of 112

Creating list from existing sequence

10 of 112

Creating list by user input

  • A list can be input by user as string input. A String is a sequence and a string input to list( ) will treat the string sequence as a list:🡪

11 of 112

Creating list by user input

12 of 112

Accessing list element

  • It can be access same like string elements.

Indexing

13 of 112

Accessing list elements

Forward

Indexing

Backward

Indexing

List

14 of 112

Length of the list

  • We can find the length of a list using len() function.
  • Example
  • A=[1,2,3,4,5,6,7,8,9]
  • len(A)
  • Result 9

15 of 112

Quiz: 1

  • If A=[1,2,3,[1,2,3],4,5,6,7,8]
  • What will be the length of list ?

16 of 112

Indexing and slicing list

  • Same like string slice
  • A=[‘a’,’b’,’c’]
  • A[2]
  • Will result c as per indexing rule
  • Slice
  • A=[‘a’,’b’,’c’,1,2,3]
  • A[2:6]

17 of 112

Indexing and slicing list

  • >>> a=['a','b','c',1,2,3]
  • >>> a[2:5]
  • ['c', 1, 2] result will display as per slicing rule
  • >>>

18 of 112

Indexing and slicing list

We have to ignore

End limit value

19 of 112

Quiz : 2

  • Generate auto list of the word “PYTHON” and print the list using for loop. Print in following pattern:🡪
  • P
  • Y
  • T
  • H
  • O
  • N

20 of 112

Membership operators

  • Both in and not in operator
  • a=list("PYTHON")
  • print(a)
  • if 'Y' in a:
  • print("yes")
  • else:
  • print("no")

21 of 112

Concatenation and replication operators

  • The + and * operators
  • The + operator used to join two list or more list.

22 of 112

23 of 112

Quiz: 3

  • #Question
  • List1=list("python")
  • List2=list("ix")
  • List3=List1+List2
  • print(List3)
  • #Ans:

24 of 112

Quiz: 4

  • #Question 2
  • List1=["python"]
  • List2=list("ix")
  • List3=List1+List2
  • print(List3)
  • #Ans:

25 of 112

Quiz: 5

  • #Question 3
  • List1=["python","jnv"]
  • List2=list("ix class")
  • List3=List1+List2
  • print(List3)
  • #Ans:

26 of 112

* operator

  • It will replicate the list
  • List=[1,2,3]
  • List*3
  • [1,2,3,1,2,3,1,2,3]

27 of 112

Slicing list

  • Extracting the part of the list
  • lst=[10,20,30,40,50,60,70,80,90]
  • slice=lst[2:5]
  • print(slice)
  • [30,40,50] will result

28 of 112

29 of 112

List updating

  • >>> list=['kn',12,23.56]
  • >>> list[2]='lm'
  • >>> list
  • ['kn', 12, 'lm']
  • >>> list[2]=56.56
  • >>> list
  • ['kn', 12, 56.56]

30 of 112

Working with list (Appending, updating, deleting on list)

  • 1. Appending element to a list:
  • Using append command for example :
  • List=[12,24,36,48]
  • List.append(60)
  • Will add single item in the end of the list

31 of 112

  • 1. Appending element to a list:

  • >>> only one item can be added in list at end, not more than one

32 of 112

  • 1. Appending element to a list:

Value

added

At last

33 of 112

  • 2. Updating list
  • A list items can be update using index number and new value.

Index number

New value

Updated value

34 of 112

Quiz: 6

  • Quiz
  • List=[11,22,33,44,55,67]
  • Change the 67 into 66

35 of 112

  • 3. Deleting element form a list
  • Using del command can remove single or all element identified by slice form a list
  • Syntax:🡪
  • del list[index number]

36 of 112

  • 3. Deleting element form a list
  • >>> list=[11,22,'jklk']
  • >>> del list[2]
  • >>> list
  • [11, 22]

37 of 112

38 of 112

List functions and methods

  • They are built in functions and methods for list manipulation.
  • Every list object you have created in python is actually an instance of list class.
  • The list manipulation function can be use as per following syntax:
  • <list object>.<method name>()

39 of 112

.index() function

  • This function will return the index of the first matched item or member from the list.
  • List.index(<item>)

40 of 112

.index() function

  • Example : 1

  • List=[10,11,12,13,14,15]
  • List.index(14)
  • It will result as 4

41 of 112

.index() function

  • Example : 1

  • Lsit1=[12,13,14,15,14,16]
  • Lsit1.index(14)
  • it will find the first match and result as 2

42 of 112

.index() function

  • If the member or item does not exist in the list it will return error not in list
  • Lsit1=[12,13,14,15,14,16]
  • List1.index(56)
  • As 56 is not a part the list1 so it will return error:
  • 56 is not in list

43 of 112

.index() function

44 of 112

List.extend() function

  • The extend() function is same like .append() function but the .append() function will add only one item at the end of the list but the extend() will add multiple element to a list or join lists.
  • List.extend(<list>)

45 of 112

List.extend() function

  • >>> list1=[1,2,3,4,5]
  • >>> list2=[5,6,5,6]
  • >>> list1.extend(list2)
  • >>> list1
  • [1, 2, 3, 4, 5, 5, 6, 5, 6]
  • >>> list2
  • [5, 6, 5, 6]

Original list1 data

list1 Data after extend

Original list2 data

46 of 112

.insert() method

  • It’s same like .append() and .extend() method used to insert element in the list.
  • But the difference it can insert anywhere in list not at the end of the list.
  • Structure :🡪
  • list.insert(<position>,<item>)

47 of 112

.insert() method

  • >>> list1=['a','e','u']
  • >>> list1.insert(2,'i')
  • >>> list1
  • ['a', 'e', 'i', 'u']
  • >>>

48 of 112

.insert() method

49 of 112

.pop() function

  • Will used to remove item or element from list and return the removed element as result.

Deleted item

50 of 112

Home work

  • Difference between append and insert function in list explain with example
  • Difference between pop and del function in list explain with example

51 of 112

Quiz: 7

  • 1. list1=[12,16,18,19,20,18]
  • list1.index(18) result ?
  • 2. colour=[‘green’,’blue’,’red’,]
  • colour.append(‘yellow’) result ?
  • 3. t1=[‘a’,’b’,’c’]
  • t1.extend(colour) result?
  • 4. colour.insert(1,’pink’) result?
  • 5. t1.pop(3) result ?

52 of 112

.remove()

  • .pop() will remove an element whose position is given what if you know the value of the element but if you don’t know the index position of the value in the list ?
  • You can use remove() function
  • list.remove(<value>)

53 of 112

.remove()

  • >>> list1.remove('i')
  • >>> list1
  • ['e', 'o', 'u']
  • >>>

Removed

54 of 112

What if item does not exist?

55 of 112

What if item exist twice?

First occurrence will be removed not all.

56 of 112

.clear() function

  • This method removes all the items from the list and makes list empty.
  • For example:
  • >>> list=[12,13,14,15,16,17,18]
  • >>> list.clear()
  • >>> list
  • []

57 of 112

If you enter a value in clear brackets.

  • List=[1,22,333,4444]
  • >>> List.clear(22)
  • Traceback (most recent call last):
  • File "<pyshell#1>", line 1, in <module>
  • List.clear(22)
  • TypeError: clear() takes no arguments (1 given)

58 of 112

.count() function

  • It will return the count of the element.
  • >>> list=[10,11,12,13,15,14]
  • >>> list.count(10)
  • 1
  • >>> list.insert(2,10)
  • >>> list.count(10)
  • 2

59 of 112

.count() function

  • >>> name=["km","KM","mm"]
  • >>> name.count(km)
  • Traceback (most recent call last):
  • File "<pyshell#1>", line 1, in <module>
  • name.count(km)
  • NameError: name 'km' is not defined
  • >>> name.count("km")
  • 1
  • >>> name.count("KM")
  • 1
  • >>> name=["km","KM","km","mm"]
  • >>> name.count("km")
  • 2

Upper case and lower case treated differently

60 of 112

.count() function

  • If the element does not exist in list it will result 0.

61 of 112

.reverse() function

  • It will reverse the items or element of the list. It will not take any argument and does not return anything.

62 of 112

.reverse() function

  • >>> list
  • [14, 15, 13, 12, 10, 11, 10]
  • >>> list.reverse()
  • >>> list
  • [10, 11, 10, 12, 13, 15, 14]

63 of 112

.reverse() function

64 of 112

.sort() function

  • This function use to sort the items in the list and by default it will sort in increasing order.
  • List.sort()

65 of 112

.sort() function

66 of 112

Sorting in decreasing order

  • It possible using two function reverse() and sort
  • >>> list=[12,10,15,16,11,13]
  • >>> list.sort(reverse=True)
  • >>> list
  • [16, 15, 13, 12, 11, 10]

67 of 112

Sorting in decreasing order

68 of 112

Comparing Lists:

  • Two lists can be compared using standard comparison operators <. <=, >, >=, = =, !=. While comparing, Python internally compares individual elements of lists in lexicographical order. This means that, each corresponding element must compare equal and the two sequences must be of the same type i.e. having comparable types of values.

69 of 112

Comparing Lists:

Two different lists

70 of 112

Comparing Lists:

Same values in both lists

71 of 112

Dictionaries

  • Another way to organize collection of data items like string, list, tuple etc.
  • Dictionaries are mutable
  • the printed order element are always different from the order which you stored
  • Basic structure of dictionary

72 of 112

Creating dictionary

  • color={“red”:”apple”,”green”:”grapes”}

Dictionary variable name

Dictionary keys

are unique

Dictionary values

73 of 112

Creating dictionary

    • dict1 = { } # Empty Dictionary
    • dict2 = {′English′ : 95, ′Maths′ : 98, ′Physics′ : 84, ′Chemistry′ : 88, ′IP′ : 99}
    • dict3 = {'Alice':'Aravali','Nagesh':'Nilgiri','Shyam':'Shivalik','Uday':'Udaygiri'}

74 of 112

Creating dictionary

    • dict4 = {1.1:1,2.2:2,3.3:3}
    • dict5 = {1:1.1,2:2.2,3:3.3}
    • dict6 = {'Even':[2,4,6,8,10],'Odd':[1,3,5,7,9],'Prime':[2,3,5,7]}
    • dict7 = {(1,2):["Apple","Bat"],(3,4):["Cat","Dog"]}

75 of 112

Creating dictionary

  • Creating an empty dictionary: An empty dictionary can be created by assigning empty curly braces to a dictionary or by using the dictionary constructor, dict( )

  • Ex: student = { }
  • student = dict( )

76 of 112

Creating dictionary

  • Creating a Dictionary from name and value Pairs: Using the dict( ) constructor of dictionary, it is possible to create a new dictionary initialized from specified set of keys and values.
  • Let see two different methods🡪

77 of 112

Creating dictionary

78 of 112

Examples (Invalid Dictionaries):�

  •  dict9 = {[1,2]:111,[3,4]:222}

  • dict10={{1:10}:100,2:20}

# Key is mutable type – list

# Key is mutable type

– Dictionary in First Item

79 of 112

Accessing element of dictionary

  • With the help of key value
  • Dictionary name[key]
  • Example
  • color={"green":"grapes","red":"apple"}
  • >>> color["green"]
  • 'grapes'

80 of 112

Membership Operators

  • Both ‘in’ and ‘not in’ operators work on dictionaries. The ‘in’ returns True if a key is present in the dictionary and the ‘not in’ returns True if a key is not present in the dictionary
  • Let see in example🡪

81 of 112

Membership Operators

82 of 112

Membership Operators

83 of 112

Membership Operators

84 of 112

Traversing a dictionary

  • The for loop make easy to traversing the dictionary
  • for item in dictionary:
  • process each item here

  • Example: computer is dictionary with following item
  • >>> computer={1:"computer",2:"mouse",3:"printer"}
  • >>> for key in computer:
  • print(key)

85 of 112

Traversing a dictionary

86 of 112

Traversing a dictionary

87 of 112

Quiz: 8

  • Write a program to create a phone dictionary for all your friends and then print it.

88 of 112

Characteristic of dictionary

  • They are mutable like list
  • Unordered set
  • Indexed by key not by numbers
  • Key must be unique

89 of 112

Updating key:value

90 of 112

Updating key:value

91 of 112

Deleting element from dic

  • del dic [key]

92 of 112

Dictionary Functions and Methods:

  • 1. len( ) :
  • Returns the length or number of �key: value pairs of the dictionary passed as the argument

93 of 112

1. len( ) :�

94 of 112

Dictionary Functions and Methods:

  • 2. get( )
  • Returns the value corresponding to the key passed as the argument
  • If the key is not present in the dictionary it will return None

95 of 112

2. get( ) �

96 of 112

2. get( ) �

97 of 112

Dictionary Functions and Methods:

  • 3. update( ) :
  • appends the key-value pair of the dictionary passed as the argument to the key-value pair of the given dictionary

98 of 112

3. update( ) :

Updated values

99 of 112

Dictionary Functions and Methods:

  • 4. keys( ) :Returns a list of keys in the dictionary

100 of 112

Dictionary Functions and Methods:

  • 5. values( ) :Returns a list of values in the dictionary

101 of 112

Ans:1

  • 9

  • To see the quiz click me:

102 of 112

Ans: 2

  • a=list("PYTHON")
  • print(a)
  • for x in a:
  • print(x)

  • To see the quiz click me:

103 of 112

Ans: 3

  • ['p', 'y', 't', 'h', 'o', 'n', 'i', 'x']

  • To see the quiz click me:

104 of 112

Ans: 4

  • ['python', 'i', 'x']

  • To see the quiz click me:

105 of 112

Ans: 5

  • ['python', 'jnv', 'i', 'x', ' ', 'c', 'l', 'a', 's', 's']

  • To see the quiz click me:

106 of 112

Ans: 6

107 of 112

Ans: 7

108 of 112

Ans:7

109 of 112

Ans: 7

110 of 112

Ans:7

111 of 112

Ans: 8

  • phonedict={“krishan”:123456,”ram”:321654}
  • for name in phonedict:
  • print(name,”:”,phonedict[name])

  • krishan : 123456
  • ram : 321654

112 of 112

Thank you