30
LUCKNOW PUBLIC SCHOOL SESSION-2019-20 STUDY MATERIAL FRAGMENT -3(part-1) SUBJECT: Informatics practices(065) CLASS-XI CHAPTERS INCLUDED: CHAPTER : List Manipulations CHAPTER : DICTIONARIES TEACHERS’ CONTRIBUTORS: GAJENDRA SINGH DHAMI, PGT (CS), SOUTH-CITY NEERU NIGAM,PGT(CS),SECTOR-I

LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

  • Upload
    others

  • View
    69

  • Download
    0

Embed Size (px)

Citation preview

Page 1: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

LUCKNOW PUBLIC SCHOOL

SESSION-2019-20

STUDY MATERIAL

FRAGMENT -3(part-1)

SUBJECT: Informatics practices(065)

CLASS-XI

CHAPTERS INCLUDED:

CHAPTER : List Manipulations

CHAPTER : DICTIONARIES

TEACHERS’ CONTRIBUTORS:

GAJENDRA SINGH DHAMI, PGT (CS), SOUTH-CITY

NEERU NIGAM,PGT(CS),SECTOR-I

Page 2: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 1

LIST MANIPULATION

The python lists are containers that are used to store a list of values of

any type.

The values in a list are called elements or sometimes items.

It is a standard data type of Python that can store a sequence of values

belonging to any type.

Python lists are mutable.

List differs from string and tuples as lists are mutable but strings and

tuples are immutable.

The lists are depicted through square brackets [ ].

Example:

L1=[„A‟,‟N‟,‟A‟,‟C‟,‟O‟,‟N‟,‟D‟,‟A‟]

0 1 2 3 4 5 6 7 Forward index

A N A C O N D A List L1 -8 -7 -6 -5 -4 -3 -2 -1 Backward Index

Creating Lists

To create a list, put a no. of expressions in square brackets. Use square

brackets [ ] to indicate the start and end of the list, and separate the items by

commas( , ).

[ ] # empty list

[ 1,2,3 ] # list of integers

[ „a‟, „b‟, „c‟ ] # list of characters

[ „one‟, „two‟, „three‟ ] # list of strings

[„a‟, 1, „b‟, 3.5, „zero‟] # mixed values list

Empty List

The empty list is [ ]. It is the list equivalent of 0 or „ ‟ and like them it also

has truth value as false. You can create an empty list by-

L = [ ] or

Page 3: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 2

L = list() #using list() method

It will generate an empty list and name that list as L

Creating list by using input(),list(),eval() method

Not a list

List having only one string element

List having only one tuple

element

List having set of elements

len() returns number of elements of list

Page 4: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 3

Nested Lists

A list can have an element in it, which itself is a list. Such a list is called a

nested list, e.g.,

L = [ 3,4,[5,6],7 ]

L is a nested list with four elements : 3, 4, [5,6]and 7.

L[2] element is a list [5,6].

Length of L is 4 as it counts [5,6] as one element.

Similarity with Strings

Length- Function len(L) returns the no. of items in the list L.

Indexing - L[i] returns the item at index i(the first item has index 0), and

Slicing - L[a:b] returns a new list, containing the objects at indexes

between a and b(excluding b)

Concatenation and replication opertors + and * can be used.

The + operator adds one list to the end of another. The * operator repeats

a list.

Accessing Individual Elements of Lists

The individual elements of a list are accessed through their indexes. List

elements are indexed, i.e., forward indexing as 0,1,2,3,…. And backward

indexing as -1,-2,-3,….

vowels = [ „a‟, „e‟, „i‟, „o‟, „u‟ ]

vowels[0] #a

vowels[4] #u

vowels[-5] #a

If you give index outside the legal indices(0 to length-1 or –length,-

length+1,…,-1), Python will raise Index Error

vowels[5] #Index Error: list index out of range

Page 5: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 4

Accessing all the elements using a loop:

Page 6: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 5

Lists are Mutable

vowels = [ „a‟, „e‟, „i‟, „o‟, „u‟ ]

vowels[0] = „A‟

vowels = [ „A‟, „e‟, „i‟, „o‟, „u‟ ]

vowels[-4] = „E‟

vowels = [ „A‟, „E‟, „i‟, „o‟, „u‟ ]

It changes the element in place in the same list as lists are mutable

#Accessing elements of a sublist

x = ['Ashok','Arjun']

print(x[0][1]) #2nd character of first element

print(x[1][3]) #4th character of second element

output:

s

u

Page 7: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 6

#Accessing elements of a sublist

z = [[1,2,3,4],[5,6,7,8]]

print(z[1][3]) # 4th element of second element([5,6,7,8) i.e nested element of

z

output:

8

#Changing print interval with third index

m = [1,2,3,4,5,6,7,8]

print (m[0:6:2]) #index are increased by 2

output:

[1, 3, 5]

Comparing Lists

For comparing operators >, <, >=, <=, the corresponding elements of

two lists must be of comparable types, otherwise python would give an

error.

Python gives the result of non equality comparisons as soon as it gets a

result in terms of true/false from corresponding elements comparison. It

jumps to next element when the first element of both lists is same and so

on.

[ 1, 2, 4 ] > [ 1, 2 ] #True

[ 1, 2, 8, 9 ] < [ 1, 2, 9, 1 ] #True

[ 1, 2, 3 ] < [ 1, [1,2] ,3 ] # Type error

Joining two List

The concatenation operator +, when used with lists, join two lists. Only two lists

can be joined.

L1,L2= [ 1, 2 ],[ 3, 4, 5 ]

L3= L1 + L2

print(L3)

Page 8: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 7

output:

[1,2,3,4,5]

L1 + 2 #Type Error

Replicating

The * operator replicate a list specified no. of times.

L1*3 = [ 1, 2, 1, 2, 1, 2, ]

Creating sublists using slicing

List slices are the sub part of a list extracted out. The list slice is itself a

list.

If you omit the first index, the slice starts at the beginning. If you omit

the second, the slice goes to the end. So if you omit both, the slice is a copy of the whole list.

Page 9: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 8

A slice operator on the left side of an assignment can update

multiple elements:

>>> t = ['a', 'b', 'c', 'd', 'e', 'f']

>>> t[1:3] = ['x', 'y'] # „b‟ and „c‟ replaced by „x‟ and „y‟

>>> print(t)

Output:

['a', 'x', 'y', 'd', 'e', 'f']

List Functions and Methods

1. index() method – The function returns the index of first matched item from

the list.

L=[13, 18, 11,16,18, 14 ]

L.index(18) #1

Returns 1st index of value 18 even if there is another 18 at index 4

2. append( ) method – The method adds an item at the end of the list.

L = [ „red‟, „blue‟ ]

L.append(„yellow‟)

Now L is updated: L = [ „red‟, „blue‟, „yellow‟ ]

3. extend( ) method – It takes a list as an argument and appends all of the

elements of the argument list to the list on which extend() is applied.

L1,L2 = [ 1, 2, 3 ], [ 4, 6 ]

L1.extend(L2)

Now L1 is updated: L1= [ 1, 2, 3, 4, 6 ]

4. insert( ) method- This function inserts an item at a given position.

L1=[1,2,3]

L1.insert(2, „4‟) # „4‟ is inserted at index 2

Now L1 is updated: L1= [ 1, 2, 4, 3 ]

Page 10: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 9

5. pop( ) method – It removes an element from the given position in the list,

and return it. If no index is specified, pop() removes and returns the last

element.

L = [ 1, 2, 4, 1, 6 ]

ele= L.pop(0) # element at 0 index deleted

Now L is updated: L = [ 2, 4, 1, 6 ] #1 is deleted

6. remove( ) method – It removes the first occurrence of given item from the

list.

L = [ 2, 4, 1, 6 ]

L.remove(1) # „1‟ is removed

print(L)

Now L is updated: [ 2, 4,6 ]

7. clear( ) method – It removes all the elements in the list and makes it empty

and return nothing.

L= [ 1, 3, 2, 5, 7 ]

L.clear()

L is updated: L = [ ]

8. count() method – It returns the count of the item that you passed as

argument.(frequency or all occurrence of an element)

L = [ 13, 18, 29, 34, 18 ]

L.count(18) # it returns 2

L.count(32) # it returns 0

9. reverse() method – It reverses the items of the list.

L1 = [ 13, 18, 29, 34, 18 ]

L1 = L.reverse()

print(L1)

Output:

Page 11: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 10

[ 18,34, 29, 18, 13 ]

10. sort() method - It sorts the items of the list in increasing order.

L = [ „a‟, „f‟, „d‟, „e‟ ]

L.sort() # For increasing order using sort

List.sort(reverse=True) # For decreasing order using sort

Output:

[ „a‟, „d‟, „e‟, „f‟ ]

[ „f‟, „e‟, „d‟, „a‟ ]

Using del command:

m = [10,20,30,40]

del m[1] # will delete 20 from the list

print(m)

del m # delete entire list

Output:

[10, 30, 40]

#Deleting using slice

m = [10,20,30]

del m[0:] #elements from 0 to last are deleted

print(m)

output:

[ ]

Page 12: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 11

Some Programs on Lists: solved

Program 1: To search a given element in a list.

Program 2: To find minimum element from a list of elements along with its

index in the list

Page 13: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 12

Output:

Program 3: To calculate mean or average of a given list of numbers.

Output:

Page 14: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 13

Program 4:To print the largest using sort function of list.

Program 5: To display elements in following pattern

Page 15: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 14

Output:

Program 6: Write a Python program to count the number of strings where the string

length is 2 or more and the first and last character are same from a given list of

strings.

Sample List : ['abc', 'xyz', 'aba', '1221']

Expected Result : 2

Output:

Page 16: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 15

EXERCISES Give outputs:

1. >>> L1=[1,2,3,4]

>>> L1.append(5) >>> L1

2. >>> L1=[1,2,3,4,5] >>> print (L1.index(2))

>>> print (L1.index(45)) 3. >>> L1=[1,2,3]

>>> L1.extend([2,3,4,5]) >>> L1

4. >>> L1=[11,22,33,44] >>> L1.insert(2,100)

>>> L1 5. >>> L1=[1,2,3,4,5]

>>> L1.pop() >>> L1

>>> L1.pop(1)

>>L1 7. L1=[1,2,3,2,3,1,2,1,3,1,3,2]

>>> L1.count(2) >>> L1.count(20)

8. >>> L1=[1,2,3,4,5] >>> L1

>>> L1.reverse() >>> L1

9. >>> L1=[15,23,6,26,11,8] >>> L1.sort()

>>> L1 >>> L1.sort(reverse=True)

>>> L1 10. >>> L1=["pankaj","gagan","amit","alankar","dinesh"]

>>> L1

>>> L1.sort() >>> L1

11. >>> L1=[15,23,6,26,11,8] >>> L1

>>> L1.clear() >>> L1

12. What is the output when following code is executed? List = [1, 5, 5, 15, 5, 1]

max = List[0] indexOfMax = 0

for i in range(1, len(List)): if List[i] > max:

max = List[i] indexOfMax = i

Page 17: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 16

print(indexOfMax) 13. What is the output when following code is executed ?

list1 = [11, 13]

list2 = list1 list1[0] = 14

print(list2) 14. What will be the output?

names1 = ['Freya', 'Mohak', 'Mahesh', 'Dwivedi'] if 'freya' in names1:

print(1) else:

print(2) 15. What will be the output?

m = [[x, x + 1, x + 2] for x in range(1, 4)] print(m)

16. How many elements are in m? m = [[x, y] for x in range(1, 4) for y in range(1, 4)]

17. What will be the output?

values = [[13, 41, 15, 11 ], [313, 16, 11, 12]] for r in values:

r.sort() for element in r:

print(element, end = " ") print()

18. What will be the output? points = [[1, 20.5], [2, 1.5], [0.5, 0.5]]

points.sort() print(points)

19. What is the output of the following code? a=[101,123,561,[178]]

b=list(a) a[3][0]=915

a[1]=134

print(b) 20 What is the output of the following code?

a=[[]]*2 a[1].append(9)

print(a) 20.What is the output when following code is executed ?

>>>names = ['Freya', 'Mohak', 'Mahesh', 'Dwivedi'] >>>print(names[-1][-1])

21. What is the output when following code is executed ?

names1 = ['Freya', 'Mohak', 'Mahesh', 'Dwivedi'] names2 = names1

names3 = names1[:] names2[0] = 'Vishal'

Page 18: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 17

names3[1] = 'Jay' sum = 0

for ls in (names1, names2, names3):

if ls[0] == ' Vishal ': sum += 2

if ls[1] == 'Jay ': sum += 5

print sum

MCQs:

1. What is the output of the following?

x = ['ab', 'cd']

for i in x:

i.upper()

print(x)

a) [„ab‟, „cd‟].

b) [„AB‟, „CD‟].

c) [None, None].

d) none of the mentioned

2. Which of the following commands will create a list?

a) list1 = list()

b) list1 = [].

c) list1 = list([1, 2, 3])

d) all of the mentioned

3. What is the output when we execute list(“hello”)?

a) [„h‟, „e‟, „l‟, „l‟, „o‟] b) [„hello‟] c) [„llo‟] d) [„olleh‟].

4. Suppose list Example is [„h‟,‟e‟,‟l‟,‟l‟,‟o‟], what is len(list Example)?

a) 5 b) 4 c) None d) Error

5. Suppose list1 is [2445, 133, 12454, 123], what is max(list1) ?

a) 2445 b) 133 c) 12454 d) 123

Page 19: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 18

6. Suppose list1 is [3, 5, 25, 1, 3], what is min(list1) ?

a) 3 b) 5 c) 25 d) 1

7. Suppose list1 is [1, 5, 9], what is sum(list1) ?

a) 1 b) 9 c) 15 d) Error

8. To shuffle the list(say list1) what function do we use ?

a) list1.shuffle ()

b) shuffle(list1)

c) random.shuffle(list1)

d) random.shuffleList(list1)

9. Suppose list1 is [4, 2, 2, 4, 5, 2, 1, 0], which of the following is correct

syntax for slicing operation?

a) print(list1[0])

b) print(list1[:2])

c) print(list1[:-2])

d) all of the mentioned

10. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1] ?

a) Error b) None c) 25 d) 2

11. Suppose list1 is [2, 33, 222, 14, 25], What is list1[:-1] ?

a) [2, 33, 222, 14]. b) Error c) 25 d) [25, 14, 222, 33, 2].

12. What is the output when following code is executed ?

>>>names = ['Amir', 'Bear', 'Charlton', 'Daman']

>>>print(names[-1][-1])

a) A b) Daman c) Error d) n

13. What is the output when following code is executed ?

names1 = ['Amir', 'Bear', 'Charlton', 'Daman']

names2 = names1

Page 20: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 19

names3 = names1[:]

names2[0] = 'Alice'

names3[1] = 'Bob'

sum = 0

for ls in (names1, names2, names3):

if ls[0] == 'Alice':

sum += 1

if ls[1] == 'Bob':

sum += 10

print sum

a) 11 b) 12 c) 21 d) 22

14. Suppose list1 is [1, 3, 2], What is list1 * 2 ?

a) [2, 6, 4].

b) [1, 3, 2, 1, 3].

c) [1, 3, 2, 1, 3, 2] .

d) [1, 3, 2, 3, 2, 1].

15. Suppose list1 = [0.5 * x for x in range(0, 4)], list1 is :

a) [0, 1, 2, 3].

b) [0, 1, 2, 3, 4].

c) [0.0, 0.5, 1.0, 1.5].

d) [0.0, 0.5, 1.0, 1.5, 2.0].

16. What is the output when following code is executed ?

>>>list1 = [11, 2, 23]

>>>list2 = [11, 2, 2]

>>>list1 < list2

a) True b) False c) Error d) None

Page 21: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 20

17. To add a new element to a list we use which command ?

a) list1.add(5)

b) list1.append(5)

c) list1.addLast(5)

d) list1.addEnd(5)

18. To insert 5 to the third position in list1, we use which command ?

a) list1.insert(3, 5)

b) list1.insert(2, 5)

c) list1.add(3, 5)

d) list1.append(3, 5)

19. To remove string “hello” from list1, we use which command ?

a) list1.remove(“hello”)

b) list1.remove(hello)

c) list1.removeAll(“hello”)

d) list1.removeOne(“hello”)

20. Suppose list1 is [3, 4, 5, 20, 5], what is list1.index(5) ?

a) 0 b) 1 c) 4 d) 2

2. What is the output of the following?

x = ['ab', 'cd']

for i in x:

x.append(i.upper())

print(x)

a) [„AB‟, „CD‟].

b) [„ab‟, „cd‟, „AB‟, „CD‟].

c) [„ab‟, „cd‟].

d) none of the mentioned

Page 22: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 21

Write programs for the following:

1. To enter and store 10 numbers in a list and print sum of elements with even

and odd values separately.

2. Store 20 numbers in a List and Search the frequency of a given element in

the list

3. Store 10 numbers in a List and count the number of primes.

4. Store names of five persons and print the name containing maximum

characters

5. Write a program to declare a python list and change the contents of the list

by adding 10 to all even elements and adding the value of next element to

all odd elements. If the last element is odd there should not be any change

to that.

6. Write a program to reverse a list without using reverse function.

if m = [1,2,3,4,5] the after rearrangement the list should become

[5,4,3,2,1]

7. Write a script to store 5 numbers in a list and rearrange the elements by

shifting each elements by one place toward right and last element to fisrt

place.

Example:if m = [1,2,3,4,5] the after rearrangement the list should

become [5,1,2,3,4]

8. Write a script to store 6 numbers in a list and rearrange the elements by

exchanging adjacent elements as mentioned below.

Example:if m = [1,2,3,4,5,9] the after rearrangement the list should

become [2,1,4,3,9,5]

9. Store 10 numbers in a list and print the second largest.

10. Write a script to store 10 elements in five nested list and printing in 5

rows and 2 columns

11. Write a script to store 20 elements in 4 nested list where each nested list

contains 5 elements and print average of each nested list one by one.

12. Enter 10 numbers and generate 2 list one containing even numbers and

other containing odd numbers.

13. Store 4 numbers in a list and display each element to its value.

Example:

If m=[3,5,4,2]

The output is:

3,3,3

5,5,5,5,5

4,4,4,4

2,2

Page 23: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

STUDY MATERIAL-XI COMPUTER-SCIENCE(083) LIST-MANIPULATION

BY: GAJENDRA S DHAMI Page 22

14. Store 10 names in a list and display the names in reverse order that

contains odd numbers of characters.

15. Store name and percentage of 10 students in 5 nested list in a list.

And display the name having highest percentage.

Example:

LST=[[“amit”,90],[“raman”,67],[“tom”,98],[“rohit”,56],[“dinesh”,78]]

The output is:

tom scored highest per%=98

Page 24: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

CHAPTER 13:DICTIONARIES

What is a dictionary in Python ???

Dictionary is a built-in data type of Python. Dictionary is like a container which associates keys

to values.

How Dictionary is different from the List ?

Dictionary is different from List in following manner..

1. Dictionary is not a sequence where as lists can be in sequence

2. Dictionaries don’t have any index numbers, whereas values of a lists are

associated or identified with the help of its associated index number

3. Keys within a dictionary must be unique, where as index of a list is not given by

user, it is always unique.

How to create a dictionary

To create a dictionary one needs to follow the given syntax

< dictionary-name> = { <key> : < value > , < key > : < value > .........}

Curly bracketes indicate the beginning and the end of dictionary

The key and the correspoing value is separated by : colon

Each entry consists of a pair < key : value > separated by a comma

For example

Monthdays={“January”:31,”February”:28,” March”,31, “April” : 30 , “ May” :31 , “

June “ : 30 , “July “: 31 , “August “ : 31 , “ September “ : 30 , “ October “: 31 ,

“November “ : 30 , “ December” : 31 }

Please see carefully

Key-value pair Key Value

“January “ : 31 “January “ 31

“February”: 28 “February” 28

Please note : if one gives a mutable type as key, Python gives an error as

“unhashable type “

For example

>>> dict = { [1,2] : “sangeeta”}

As the key has been given as list

Page 25: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

Initializing a Dictionary

1. To initialize a dictionary , give key : value pairs , separated by

commas and enclosed in curly braces .....

Result = { “ Abhai “ : 88 , “ Amit “ : 90 , “ Atul” : 95 , “ Deepti “ : 56 }

2. Specify key : value pairs as arguments to dict ( ) function

One can pass keys and values as parameters to the function dict ( ), and create a

dictionary

result=dict(name="amit",per=99)

>>> result

{'name': 'amit', 'per': 99}

3 Specify keys separately and corresponding values separately

In this method , the keys and values are enclosed separately in parentheses

and are given as arguments to the zip( ) function, which is then given as argument of

dict ( )

For example

result=dict(zip(("name","per","result"),("Ankita",99,"PASS")))

>>> result

{'name': 'Ankita', 'per': 99, 'result': 'PASS'}

Accessing Elements of a Dictionary

While accessing elements from the dictionary one needs a key. While elements

from the list can be accesed through its index number. To access an element from a

dictionary, follow the given syntax

< dictionary-name > [ < key >]

For example

>>> monthday[“January”]

Python return... 31

>>> print (“there are “ , monthday[“January”] ,” days in January “ )

Page 26: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

Will print

There are 31 days in January

Traversing a Dictionary

Traversing means accessing and processing each element of a dictionary. To

access each element of a dictionary we take help of Python loop as we do take in List

For < item > in < dictionary > :

Process each element

For example

Monthdays={“January”:31,”February”:28,” March”,31, “April” : 30 , “ May” :31 , “

June “ : 30 , “July “: 31 , “August “ : 31 , “ September “ : 30 , “ October “: 31 ,

“November “ : 30 , “ December” : 31 }

To see all the elements of the ab ove dictionary, we give the following loop

For month in dictionary :

Print ( month , “:” , monthdays[month] )

The output will be

January : 31

Febraury : 28

March : 31

April : 30

.....

....

Decemeber : 31

In the above example month is the loop variable, which gets assigned with the keys

of monthdays dictionary , one at a time

Accessing keys or values

To see all the keys in a dictionary in one go, one can write < dictionary>.keys()

and to see all the values in one go , one must write < dictionary>. Values ( ) For example

Page 27: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

>> week = { “Sunday” : 1 , “Monday “ : 2 , “Tuesday “: 3 , “Wednesday “ : 4 ,

“Thursday “ : 5 , “ Friday “ : 6 , “ Saturday “ : 7 }

>>> week.keys ( )

Will show

dict_keys(['sunday', ' monday '])

to see the values of the dictionary element

>>> week. Values ( )

Will show

dict_values([1, 2])

one can also convert the sequence returned by keys ( ) and values ( ) functions by

using list ( ) as shown belo w :

>>> list (week. Keys ( ) )

Will show the foloowing

['sunday', ' monday ']

>>> list ( week.values ( ) )

Will show the following

[1 , 2 ]

Adding Elements to Dictionary

One can add new elements to a dictionary using assignment as per

following syntax. The only issue is , entered key must not already be

available , i.e it must be unique

For example :

< dictionary > [ < key > ] =<value >

result["totalmarks"]=499

>>> result

{'name': 'Ankita', 'per': 99, 'result': 'PASS', 'totalmarks': 499}

Updating Existing Elements in a Dictionary

Page 28: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

To update an element’s value is very much similary to adding a new value in to a

dictionary. In this case too we assign the updated values in to the key.

For example

result["per"]=99.5

>>> result

{'name': 'Ankita', 'per': 99.5, 'result': 'PASS', 'totalmarks': 499}

Deleting Elements from a Dictionary

There are two methods for deleting elements from a dictionary

1. To delete a dictionary element, one can use del command. The syntax for doing

so is as follows

Del < dictionary > [ <key>]

For example

result={'name': 'Ankita', 'per': 99, 'result': 'PASS', 'totalmarks': 499}

>>> del result['result']

>>> result

{'name': 'Ankita', 'per': 99, 'totalmarks': 499}

2. Another method to delete elements from a dictionary is by using pop( ) method as

per the following syntax..

<dictionary>.pop(<key>)

For example

result={'name': 'Ankita', 'per': 99, 'result': 'PASS', 'totalmarks': 499}

>>> result.pop('per')

99

>>> result

{'name': 'Ankita', 'result': 'PASS', 'totalmarks': 499}

Checking for existence of a key

The existence of an element in a dictionary can be checked with the help of in

and not in operators. The syntax to use these operators is as follows

< key > in < dictionary >

< key > not in < dictionary >

Page 29: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

The in operator will return true if the given key is present in the dictionary

, otherwise false.

The not in operator will return true if the given key is not present in the

dictionary, otherwise false.

For example

result={'name': 'Ankita', 'result': 'PASS', 'totalmarks': 499}

>>> result={'name': 'Ankita', 'per': 99, 'result': 'PASS', 'totalmarks': 499}

>>> 'percentage' in result

False

>>> 'percentage' not in result

True

FUNCTIONS AND METHODS WITH DICTIONARY

Python provides some built-in methods and functions to ease our work. They are

as follows

1. len ( ) method

This method is used to tell the length i.e total number of elements present in to

the dictionary. The syntax to use len ( ) method is as follow :

len ( < dictionary> )

for example

>>>result={'name': 'Ankita', 'per': 99, 'result': 'PASS', 'totalmarks': 499}

>>> len(result)

4

2. clear ( ) method

This method removes all the items from the dictionary and dictionary

becomes empty dictionary after this method. The syntax to use this method is.

<dictionary > . clear ( )

for example

>>>result={'name': 'Ankita', 'per': 99, 'result': 'PASS', 'totalmarks': 499}

>>> result.clear()

>>> result

{}

Page 30: LUCKNOW PUBLIC SCHOOL - priyadarshani.thelps.edu.inpriyadarshani.thelps.edu.in/UploadedFiles/Update...Creating list by using input(),list(),eval() method Not a list List having only

3. get( ) method

This method is used to get an element in reference to the given key. The

syntax is as follows

< dictionary>.get(key, < message > )

for example

>>> result={'name': 'Ankita', 'per': 99, 'result': 'PASS', 'totalmarks': 499}

>>> result.get('result')

'PASS'

>>> result.get('percentage')

>>> result.get('percentage','wrong key ')

'wrong key '

4. keys( ) method

This method returns all of the keys present in the dictionary as a sequence of

keys. The syntax to use it is as follows

<dictionary> . keys ( )

For example

>>> result.keys()

dict_keys(['name', 'per', 'result', 'totalmarks'])

5. values( ) method

This method is used to return all the values present in to the dictionary as a

sequence of values. The syntax to use it is as follows

< dictionary> . values ()

For example

>>> result.values()

dict_values(['Ankita', 99, 'PASS', 499])

6. update( ) method

This method merges key:value paris from the new dictionary into the original

dictionary, adding or replacing as needed. The items in the new dictionary are

added to the old one and override any items already there with the same keys.

The syntax is

< dictionary>.update ( < other-dictionary>)

stud1={'name':'ANKUR' , ' CLASS': 'XIIA'}

>>> stud2={'name':' KAVITA','CLASS':'XIIB' ,'RESULT':'PASS'}

>>> stud1.update(stud2)

>>> stud1

{'name': ' KAVITA', ' CLASS': 'XIIA', 'CLASS': 'XIIB', 'RESULT': 'PASS'}