0% found this document useful (0 votes)
21 views26 pages

Unit-2 ch-11 Lists

Uploaded by

kakalachu6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views26 pages

Unit-2 ch-11 Lists

Uploaded by

kakalachu6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Chapter-11 : List Manipulation

Data Structure
• A data structure is a group of data elements that are put together under one name.
• It defines a particular way of storing and organizing data in a computer so that it can be
used efficiently.
• List, Tuple, Dictionary are compound data structures.

Sequence
• It is the most basic data structure where each element has a specific index.
• Index value starts from 0 and goes on increasing.
• It is an ordered set.

List
➢ A list is a data-structure, or it can be considered a container that can be used to store
multiple data at once.
➢ A list is also a dynamic and mutable type, i.e., we can add and delete elements from the list
at any time.
➢ The values that make up a list are called its elements. Each list value is a single element in
the list.
➢ The elements are indexed according to a sequence and the indexing is done with 0 as the
first index.
➢ It is a compound data types, used to group together other values.
➢ List is the most versatile data structure, which can be written as a list of comma-separated
values (items) between square brackets.
➢ List items may or may not have the same type.

Declaring/Creating a List
To create a list, we separate the elements with a comma and enclose them with a bracket “[]”.
The syntax is:
<name of list> = [ <value>, <value>, <value> ]

Examples :
Listname=[ ]
L1=[ ] # it creates an empty list
L2=[1,2,3,4,5] # it creates a list of 5 integers

1|Page
L3=[‘a’, ‘e’,’i’,’o’,’u’]
L4=[“ TAFS“ , “ AFGJI“ , “ AFBBS“ ]
L5=[1,’a’, “ TAFS“ ] # a list with multiple type values

Accessing / Printing list elements


➢ We can access individual list elements using indexing and a range of elements using
slicing.
➢ A list index starts from 0. Python indexes the list element from left to right and from right
end to left.
➢ From left to right, the first element of a list has the index 0 and from right end to left, the
extreme right index element of a list is –1.
➢ Individual elements in a list can be accessed by specifying the list name followed by a
number in square brackets ( [ ] ).

Traversing a List

2|Page
Aliasing in lists
In python, variable refer to objects. When we assign one variable to another, both variables refer
to the same object.
A = [10,20,30]
B=A
In this case both lists refer to the same object , i.e. the memory location is same and the list has
two different names. This is called aliasing of lists. Address of both the lists will be same.
In case of aliasing, changes made to one list affect to other list also.
B[0] = 25
print A displays [25,20,30]

Creating list from existing list : Using aliasing


Let list1 = [1,2,3,4,5]
If we write list2 = list1
Then it copies all values of list1 to list2 as well as address of both lists will be same.
Any change made to one list is reflected in the other list also.
List2 [ 3 ] = 14
print (list2) gives [ 1, 2, 3, 14, 5 ]
print (list1) also prints [ 1, 2, 3, 14, 5 ]

3|Page
In case of aliasing, both the names refer to the same memory locations. Hence, changes
made in one list name are reflected in the other as well.

Cloning a list
Method 1 : Creating list from existing list : Using slicing operation
But using the slice operation, if we create a new list, then it has separate id, i.e address.
List3= list1[ : ]
It displays all values of list1 but id will be different.
This process is called Cloning list
➢ Selecting a slice is similar to selecting an element(s) of a list.
➢ Subsets of lists can be taken using the slice operator with two indices in square brackets
separated by a colon ( [m:n] ).
➢ The operator [m:n] returns the part of the list from the mth position and up to but not
including position n, i.e., n – 1.
➢ In case of slicing, both the lists are different, i.e. they DO NOT refer to the same
memory locations. Hence, changes made in one list name are NOT REFLECTED in
the other.

Method 2 of Cloning a List : using copy function()

4|Page
Creating list from existing list : using list keyword
Syntax : Newlistname = list(sequence/string )
Example :
>>>list1 = list(‘computer’) list is the keyword
>>>list1
>>> [‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’]

Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on.

Creating list from existing list : using slicing operation


list2 = list1[:] or list2=list1 # copies whole list
list3 = list1[1:4] # copies only first 3 elements
Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on.

Slicing operation on lists

5|Page
List is mutable
➢ Lists are mutable, which means we can change their elements.
➢ Using the bracket operator ([ ]) on the left side of an assignment, we can update one of the
elements.
➢ For example:
# a list with five friends
>>> friends = ['Anmol', 'Kiran', 'Vimal', 'Sidharth', 'Riya']
# lists 0th position value changed with new name Jatin
>>> friends[0] = 'Jatin'
# lists last position value changed with new name Vidya
>>> friends[-1] = 'Vidya'
>>> print (friends)
['Jatin', 'Kiran', 'Vimal', 'Sidharth', 'Vidya']

This operation could not be performed with strings, as strings are immutable in nature.

Traversing a list
1. Using ‘in’ operator with for loop
output
list1 = [ ‘p’ , ’y’ , ’t’ ] p
for i in list1 : # i is individual item of list y
t
print(i)

2. Using range function


output
list1=[ ‘p’ , ’y’ , ’t’ ]
p
n=len(list1) y
for i in range(n) : # i is the index value t
print(list1[i])

6|Page
3. Using range function (with negative indexing)
list1=[‘p’,’y’,’t’] output
n=len(list1) p
for i in range(-n,0): y
t
print(list1[i])

Comparing Lists
➢ We can compare lists using relational operators (< <= > >= == ).
➢ It compares lists in lexicographic order.
➢ No. of elements does not matter while comparing. It compares element wise only till the first
difference is encountered
➢ Example :
[1,2,3,4] < [4,5,6] gives True
[1,2,3,4] < [1,2,5,3] gives True
[1,2,3,4] < [1,2,3,2] gives False

✓ No. of elements does not matter.


✓ It compares element wise only till the first difference is encountered

Operations on Lists
1. Concatenation : Multiple sequence or lists can be combined together
list1 = [‘red’, ‘blue’, ’green’]
list2 = [10,20,30]
list1 = list1 + [‘yellow’]
print (list1) will display [‘red’,‘blue’, ’green’, ‘yellow’]

# adding two lists


list3 = list1 + list2 will display [‘red’, ‘blue’, ’green’, ‘yellow’,10,20,30]
7|Page
2. Repetition/Replication : Lists can be replicated or repeated or repeatedly concatenated with
the asterisk operator "*".
Note : A list can only be multiplied with an integer, It cannot be multiplied with another list
or any string.

Multiplying a list with negative number or 0 returns blank list

3. Membership testing ( in / not in)


list1=[10,20,30,40,50]
print( 40 in list1) displays True
list1=[10,20,30,40,50]
print( 50 not in list1) displays False

8|Page
4. Indexing
list1=[10,20,30,40,50]
print( list1[2]) will display 30
print( list1[-3]) will display 30

5. Slicing
list1= [ ‘violet’, ‘indigo’, ‘blue’, ’green’ ,‘yellow’, ‘orange’, ‘red’]
print(list1[1:4]) displays [ ‘indigo’, ‘blue’, ’green’ ]
print( list1[1:6:2]) displays [ ‘indigo’, ’green’ , ‘orange’ ]
print( list1[2:]) display [ ‘blue’, ’green’ ,‘yellow’, ‘orange’, ‘red’]
print( list1[:4]) display [ ‘violet’, ‘indigo’, ‘blue’, ’green’ ,‘yellow’ ]
print( list1[-3:]) displays [ ‘yellow’, ‘orange’, ‘red’ ]
print( list1[ : -2]) displays [ ‘violet’, ‘indigo’, ‘blue’, ’green’ ,‘yellow’]

✓ For max, min function list should contain homogenous elements. i.e either int/float ,
single character/string.
✓ Sum function is used only for numerical items in list

6. max () : It returns maximum value in the list


list1= [ 1,6,2,9,3]
print(max(list1)) gives 9

7. min () : it returns minimum of list values


list1= [ 1,6,2,9,3]
print(min(list1)) gives 1

9|Page
Max and min functions using string
max()
It returns the highest element from the list
n=max(listname)
list1 = [ ‘a’, ‘b’, ‘c’, ‘d’, ’b’, ‘c’, ‘b’ ]
n=max(list1)
print(n) ‘d’

min()
It returns the lowest element from the list
n=min(listname)
list1 = [ ‘a’, ‘b’, ‘c’, ‘d’, ’b’, ‘c’, ‘b’ ]
n=min(list1)
print(n) ‘a’

8. sum () : it returns sum of elements of list items. The elements of the list should be numeric in
this case.
list1= [ 1,6,2,9,3]
print(sum(list1)) gives 21

10 | P a g e
9. all () : It returns true if all items are not equal to 0
list1= [ 1,6,2,9,3]
list2=[ 0,6,9,0]
print(all(list1)) gives True
print(all(list2)) gives False

10. any () : it returns true if any one item of the list is not equal to 0
list1= [ 1,6,2,9,3]
list2=[ 0,6,9,0]
print(any(list1)) gives True
print(any(list2)) gives True

11. list () : It converts any data structure into list


list1 = list("HELLO")
print(list1) displays ['H', 'E', 'L', 'L', 'O']

12. sorted () : it creates a new sorted list in ascending order by default


list1= [ 1,6,2,9,3]
list2=sorted(list1)
print(list2) gives [ 1,2,3,6,9 ]

To make it descending order use reverse=True


list3 = sorted (list1, reverse=True) gives [ 9,6,3,2,1 ]

11 | P a g e
Methods / Functions in list
1. append() : new values can be added at end of list
Syntax : list.append(item)
list1 = [ 10,20,30,40 ]
list1.append(50)
print(list1) will display [ 10,20,30,40 ,50 ]

new list(nested) can be added at end of list also


list1 = [ 10,20,30,40 ]
list2=[50,60]
list1.append(list2)
print(list1) will display [ 10,20,30,40, [50,60] ]

2. extend() : one list will be added at the end of another list


Syntax : list1.extend(list2)

12 | P a g e
3. insert() : An element will be inserted at a specified index.
Syntax : listname.insert (indexnumber, value)
Example :
list1 = [ ‘a’, ‘b’, ‘c’, ‘d’ ]
list1.insert(2,’B’)
print(list1) will display [ ‘a’, ‘b’, ’B’, ‘c’, ‘d’ ]

If element will be added at a index which is out of bound, i.e beyond length the item will be
added at end itself with new index value. Similarly for negative index if out of bound, it
added at 0th position.

4. reverse() : list will be reversed. List will be updated also


Syntax : list1.reverse()
Example :
list1 = [ 10,20,30,40 ]
list2 = [ ‘a’, ‘b’, ‘c’, ‘d’ ]
list1.reverse()
print(list1) will display [ 40,30,20,10 ]

13 | P a g e
5. Index () : It returns the index value of first matched item in the list. If not found it raises an
error
Syntax : n= listname.index( value)
Example :
list1 = [ ‘a’, ‘b’, ‘c’, ‘d’, ’b’, ‘c’, ‘b’ ]
n=list1.index(‘b’)
print(n) will display 1

6. len() : it counts the number of elements in a list.


Syntax : n=len(list1)
Example :
list1 = [ 10,20,30,40 ]
list2 = [ ‘a’, ‘b’, ‘c’, ‘d’ ]
n=len(list1)
print(n) will display 4

7. sort() : list will be arranged either in ascending order or descending order.


Syntax : listname.sort() # ascending by default
listname.sort( reverse=True) # descending order
Example :
list1 = [ ‘a’, ‘b’, ‘c’, ‘d’, ’b’, ‘c’, ‘b’ ]
list1.sort() will display [‘a’, ‘b’, ’b’, ’b’, ’c’, ’c’, ’d’ ]
Note: list will be updated also

Difference between sorted() and sort()

14 | P a g e
➢ list will be arranged either in ascending order or descending order by using key =function.
listname.sort(key=len) # by length of item wise
listname.sort( key=len, reverse=True) # descending order

➢ list will be updated also


➢ The order of elements in the list does not change, it just rearranges them as per their
length.

8. count() : it counts how many number of times an element exist. It returns 0 if element not
found
Syntax : n=listname.count(item)

15 | P a g e
9. clear() : All elements will be deleted and list becomes empty list
Syntax : listname.clear()
Example :
list1 = [ ‘a’, ‘b’, ‘c’, ‘d’, ’b’, ‘c’, ‘b’ ]
list1.clear() will display [ ]
Note: list will be updated to empty list

Deletion Operation Functions in list


There are many methods of deleting element from list
➢ If index is known, you can use pop()
➢ If element is known you can use remove()
➢ To remove more than one element del() with slice can be used

10. pop() : It removes the element from specified index and returns the element
Syntax : n=listname.pop(indexnumber)
n=listname.pop()
Example :
list1 = [ ‘a’, ‘b’, ‘c’, ‘d’, ’b’, ‘c’, ‘b’ ]
n=list1.pop(3) will delete ‘d’
m=list1.pop() will delete ‘b’
Note: if index value not given, last element will be deleted

11. del() : It removes the element from specified index but does not returns the element.
Syntax : del ( listname [indexnumber] )
Example :
list1 = [ ‘a’, ‘b’, ‘c’, ‘d’, ’b’, ‘c’, ‘b’ ]
del( list1[3] ) will delete d

12. del( ) with slicing


Syntax : del listname [start indexnumber : end indexnumber ]
Example :
list1 = [ ‘a’, ‘b’, ‘c’, ‘d’, ’b’, ‘c’, ‘b’ ]
del( list1[2:5] ) will delete c, d ,b
now list becomes [ ‘a’, ‘b’, ‘c’, ‘b’ ]

16 | P a g e
13. remove() : It removes the first occurrence of the element from the list. A valueError
exception is raised if item is not found in the list.
Syntax : listname.remove(item)
Example :
list1 = [ ‘a’, ‘b’, ‘c’, ‘d’, ’b’, ‘c’, ‘b’ ]
list1.remove(‘b’)
print(list1) displays [ ‘a’, ‘c’, ‘d’, ’b’, ‘c’, ‘b’ ]

14. copy()
Syntax : list2=list1.copy() # list1 is an existing list
Here id of both lists will be different
Example :
list1 = [ ‘a’, ‘b’, ‘c’, ‘d’, ’b’, ‘c’, ‘b’ ]
list2=list1.copy()

17 | P a g e
PROGRAMS ON LISTS

create a list and add n elements to it

18 | P a g e
WAP to create a list of 5 names of your class and print it in reverse order

A list called Festival is given with following elements: Festival = ['Lumbini',


'Mopin', 'Bihu', 'Chhath', 'Onam', 'Lohri', 'Pongal', 'Garba']
Write a program to enter a festival name and search whether the name present
in the list or not using in operator. Print appropriate message.

19 | P a g e
A list called Festival is given with following elements: Festival = ['Lumbini',
'Mopin', 'Bihu', 'Chhath', 'Onam', 'Lohri', 'Pongal', 'Garba'] … Write a program
to enter a festival name and search whether the name present in the list or not
without using membership operator.

Write a program to input certain numbers into a list and find the largest and
smallest number in that list without using max() and min() function.

20 | P a g e
WAP to search for a particular element in the list.

WAP to search for a particular element in the list and display its all
occurrences.

21 | P a g e
Write a program to enter a string and count total number of word The/the in
the given string. If the input text is: He is playing in the ground. She is the only
player. The playing condition is good.
The output is: Count of The/the in text: 3

Write a program to enter a string and count total number of word The/the in
the given string. If the input text is: He is playing in the ground. She is the only
player. The playing condition is good.
The output is: Count of The/the in text: 3

22 | P a g e
WAP to delete all even numbers from the list.

Write a program to display the city names from a list of STATES, which are
starting with alphabet M.
For example: If the list STATES contains ["MP", "UP", "WB", "TN", "MH",
"MZ", "DL", "BH", "RJ", "HR"]
The following should get displayed:
MP MH MZ

Python offers many ways to access elements of list


1. Using enumerate() function
list1 = [ 5,1,7,3,8,2]
for index , I in enumerate(list1):
print( I , “ is at the index “, index)

23 | P a g e
2. Using range() function
list1 = [ 5,1,7,3,8,2]
for I in range ( len(list1) ):
print( list[I] )

3. Using an iterator: built in iter()


you can create an iterator using iter(). The iterator is used to loop over the elements of the
list. The iterator fetches the value and then automatically points to the next element in the
list when it used with the next() method
list1=[ 5,1,7,3,8,2]
it=iter(list1)
for I in range(len(list1)):
print(“ Element at index”,I, “is”, next(it))

Matrix using list( nested list)


Matrix is the collection elements arranged in tabular form i.e in row and column forms

Using for loop


M = [ [1,2,3] , [4,5,6] , [7,8,9] ]
for i in range (3):
for j in range(3):
print(M[i][j], end=“\t”)
print()

using while loop


M = [ [1,2,3] , [4,5,6] , [7,8,9] ]
i=0
while i<3:
j=0
while j<3:
print (M[i][j], end=“\t”)
j=j+1
print()
i=i+1

24 | P a g e
Creating and displaying a matrix
Method 1

Method 2

Sorting in list
Sorting means arranging elements either in ascending order or descending order

1. Bubble sort
It compares between two consecutive elements of array and arranged in order if required. After
comparison of each element, the smallest or largest element will be bubbled up to the last
position. That is called 1st pass. The process will continue from beginning to get 2nd
smallest/largest in the 2nd last position and so on.

25 | P a g e
Bubble Sort Code :

26 | P a g e

You might also like