[go: up one dir, main page]

0% found this document useful (0 votes)
13 views20 pages

12th C-4 Reproductive Health

Chapter 11 covers list manipulation in Python, explaining that lists are mutable ordered sequences that can contain elements of different data types. It details how to access, modify, and perform operations on lists, including concatenation, repetition, and membership checks, as well as various built-in methods for list management. Additionally, the chapter discusses nested lists, copying lists, and provides example programs for practical applications.
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)
13 views20 pages

12th C-4 Reproductive Health

Chapter 11 covers list manipulation in Python, explaining that lists are mutable ordered sequences that can contain elements of different data types. It details how to access, modify, and perform operations on lists, including concatenation, repetition, and membership checks, as well as various built-in methods for list management. Additionally, the chapter discusses nested lists, copying lists, and provides example programs for practical applications.
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/ 20

CHAPTER -11 List Manipulation

The data type list is an ordered sequence which is mutable and made up of one or more elements. Unlike a string which
consists of only characters, a list can have elements of different data types, such as integer, float, string, tuple or even
another list. A list is very useful to group together elements of mixed data types. Elements of a list are enclosed in square
brackets and are separated by comma. Like string indices, list indices also start from 0.
Examples
>>> list1 = [2,4,6,8,10,12] #list1 is the list of six even numbers
>>> print(list1)
[2, 4, 6, 8, 10, 12]
>>> list2 = ['a','e','i','o','u'] #list2 is the list of vowels
>>> print(list2)
['a', 'e', 'i', 'o', 'u']
>>> list3 = [100,23.5,'Hello'] #list3 is the list of mixed data types
>>> print(list3)
[100, 23.5, 'Hello']
>>> list4 =[['Physics',101],['Chemistry',202], ['Maths',303]] #list4 is the list of lists called nested
>>> print(list4)
[['Physics', 101], ['Chemistry', 202],['Maths', 303]]
Accessing Elements in a List
The elements of a list are accessed in the same way as characters are accessed in a string.
>>> list1 = [2,4,6,8,10,12]
>>> list1[0] #return first element of list1
2
>>> list1[3] #return fourth element of list1
8
>>> list1[15]
IndexError: list index out of range
>>> list1[1+4] #an expression resulting in an integer index
12
>>> list1[-1] #return first element from right
12
>>> n = len(list1) #length of the list list1 is assigned to n
>>> print(n)
6
>>> list1[n-1] #return the last element of the list1
12
>>> list1[-n] #return the first element of list1
2
Lists are Mutable
In Python, lists are mutable. It means that the contents of the list can be changed after it has been created.
>>> list1 = ['Red','Green','Blue','Orange'] #List list1 of colors
>>> list1[3] = 'Black‘ #change/override the fourth element of list1
>>> list1 #print the modified list list1
['Red', 'Green', 'Blue', 'Black']
List Operations
The data type list allows manipulation of its contents through various operations as shown below.
Concatenation
Python allows us to join two or more lists using concatenation operator depicted by the symbol +.
>>> list1 = [1,3,5,7,9] #list1 is list of first five odd integers
>>> list2 = [2,4,6,8,10] #list2 is list of first five even integers
>>> list1 + list2 #elements of list1 followed by list2
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
>>> list3 = ['Red','Green','Blue']
>>> list4 = ['Cyan', 'Magenta', 'Yellow','Black']
>>> list3 + list4
['Red','Green','Blue','Cyan','Magenta','Yellow','Black']
Note that, there is no change in ongoing lists, i.e.,list1, list2, list3, list4 remain the same after concatenation operation. If
we want to merge two lists, then we should use an assignment statement to assign the merged list to another list. The
concatenation operator '+’ requires that the operands should be of list type only. If we try to concatenate a list with
elements of some other data type, TypeError occurs.
>>> list1 = [1,2,3]
>>> str1 = "abc"
>>> list1 + str1
TypeError: can only concatenate list (not "str") to list
Repetition
Python allows us to replicate a list using repetition
operator depicted by symbol *.
>>> list1 = ['Hello'] #elements of list1 repeated 4 times
>>> list1 * 4
['Hello', 'Hello', 'Hello', 'Hello']
Membership
Like strings, the membership operators in checks if
the element is present in the list and returns True, else
returns False.
>>> list1 = ['Red','Green','Blue']
>>> 'Green' in list1
True
>>> 'Cyan' in list1
False
The not in operator returns True if the element is not
present in the list, else it returns False.
>>> list1 = ['Red','Green','Blue']
>>> 'Cyan' not in list1
True
>>> 'Green' not in list1
False
Slicing
Like strings, the slicing operation can also be applied to lists.
>>> list1 =['Red','Green','Blue','Cyan','Magenta','Yellow','Black']
>>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow']
>>> list1[2:20] #second index is out of range
['Blue', 'Cyan', 'Magenta', 'Yellow','Black']
>>> list1[7:2] #first index > second index
[] #results in an empty list
>>> list1[:5] #first index missing
['Red','Green','Blue','Cyan','Magenta']
>>> list1[0:6:2] #slicing with a given step size
['Red','Blue','Magenta']
#negative indexes
>>> list1[-6:-2] #elements at index -6,-5,-4,-3 are sliced
['Green','Blue','Cyan','Magenta']
>>> list1[::2] #step size 2 on entire list
['Red','Blue','Magenta','Black']
>>> list1[::-1] #negative step size whole list in the reverse order
['Black','Yellow','Magenta','Cyan','Blue','Green','Red']
Traversing a List
Each element of the list can be accessed or traverse a list using a for loop or a while loop.
List Traversal Using for Loop:
list1 = ['Red','Green','Blue','Yellow','Black']
for item in list1:
print(item)
Output:
Red
Green
Blue
Yellow
Black
List traversal using range() and len() functions:
list1 = ['Red','Green','Blue','Yellow','Black']
size=len(list1)
for i in range(len(list1)):
print(list1[i])
Output:
Red
Green
Blue
Yell
List Traversal Using while Loop:
list1 = ['Red','Green','Blue','Yellow','Black']
size=len(list1)
i=0
while i < size):
print(list1[i])
i += 1
Output:
Red
Green
Blue
Yellow
Black
List Methods and Built-in Functions
The data type list has several built-in methods that are useful in programming. Some of them are

METHOD DESCRIPTION EXAMPLE


len() Returns the length of the list passed as >>> list1 = [10,20,30,40,50]
the argument >>> len(list1)
5
METHOD DESCRIPTION EXAMPLE
len() Return the length of the list >>> list1 = [10,20,30,40,50]
>>> len(list1)
5

list() Creates an empty list if no argument(value) is >>> list1 = list()


provuded. >>> list1
[]
Creates a list if any sequence is passed >>> str1 = 'aeiou'
>>> list1 = list(str1)
>>> list1
['a', 'e', 'i', 'o', 'u']

append() Adds a single element at the end of the list >>> list1 = [10,20,30,40]
>>> list1.append(50)
**The single element can also be a list >>> list1
[10, 20, 30, 40, 50]
>>> list1 = [10,20,30,40]
>>> list1.append([50,60])
>>> list1
[10, 20, 30, 40, [50, 60]]
METHOD DESCRIPTION EXAMPLE
extend() Appends each element of the list passed >>> list1 = [10,20,30]
as argument to the end of the given list >>> list2 = [40,50]
>>> list1.extend(list2)
>>> list1
[10, 20, 30, 40, 50]
insert() Inserts an element at a particular index >>> list1 = [10,20,30,40,50]
in the list >>> list1.insert(2,25)
>>> list1
[10, 20, 25, 30, 40, 50]
>>> list1.insert(0,5)
>>> list1
[5, 10, 20, 25, 30, 40, 50]
count() Returns the number of times a given >>> list1 = [10,20,30,10,40,10]
element appears in the list >>> list1.count(10)
3
>>> list1.count(90)
0
index() Returns index of the first occurrence of >>> list1 = [10,20,30,20,40,10]
the element in the list. If the element is >>> list1.index(20)
not present, ValueError is generated 1
>>> list1.index(90)
ValueError: 90 is not in list
METHOD DESCRIPTION EXAMPLE
remove() Removes the given element from the list. If the element >>> list1 = [10,20,30,40,50,30]
is present multiple times, only the first occurrence is >>> list1.remove(30)
removed. If the element is not present, then ValueError >>> list1
is generated [10, 20, 40, 50, 30]
>>> list1.remove(90)
ValueError:list.remove(x): x not in list
pop() Returns the element whose index is passed as parameter >>> list1 = [10,20,30,40,50,60]
to this function and also removes it from the list. If no >>> list1.pop(3)
parameter is given, then it returns and removes the last 40
element of the list >>> list1
[10, 20, 30, 50, 60]
>>> list1 = [10,20,30,40,50,60]
>>> list1.pop()
60
>>> list1
[10, 20, 30, 40, 50]
reverse() Reverses the order of elements in the >>> list1 = [34,66,12,89,28,99]
given list >>> list1.reverse()
>>> list1
[ 99, 28, 89, 12, 66, 34]
>>> list1 = ['Tiger' ,'Zebra' ,'Lion' , 'Cat' ,'Elephant' ,'Dog']
>>> list1.reverse()
>>> list1
['Dog', 'Elephant', 'Cat','Lion', 'Zebra', 'Tiger']
METHOD DESCRIPTION EXAMPLE
sort() Sorts the elements of the given list in-place >>>list1 = ['Tiger','Zebra','Lion','Cat', 'Elephant' ,'Dog']
>>> list1.sort()
>>> list1
['Cat', 'Dog', 'Elephant', 'Lion','Tiger', 'Zebra']
>>> list1 = [34,66,12,89,28,99]
>>> list1.sort(reverse = True)
>>> list1
[99,89,66,34,28,12]

sorted() It takes a list as parameter and creates a new list >>> list1 = [23,45,11,67,85,56]
consisting of the same elements arranged in sorted >>> list2 = sorted(list1)
order >>> list1
[23, 45, 11, 67, 85, 56]
>>> list2
[11, 23, 45, 56, 67, 85]
min() Returns minimum or smallest element of the list >>> list1 = [34,12,63,39,92,44]
>>> min(list1)
12
max() Returns maximum or largest element of >>> max(list1)
the list 92
sum() Returns sum of the elements of the list >>> sum(list1)
284
Nested Lists
When a list appears as an element of another list, it is called a nested list.
>>> list1 = [1,2,'a','c',[6,7,8],4,9] #fifth element of list is also a list
>>> list1[4]
[6, 7, 8]
To access the element of the nested list of list1, we have to specify two indices list1[i][j]. The first index i will take us to the
desired nested list and second index j will take us to the desired element in that nested list.
>>> list1[4][1]
7
Here index i gives the fifth element of list1 which is a list and index j gives the second element in the nested list
Copying Lists
Given a list, the simplest way to make a copy of the list is to assign it to another list.
>>> list1 = [1,2,3]
>>> list2 = list1
>>> list1
[1, 2, 3]
>>> list2
[1, 2, 3]
The statement list2 = list1 does not create a new list. Rather, it just makes list1 and list2 refer to the same list object. Here list2
actually becomes an alias of list1. Therefore, any changes made to either of them will be reflected in the other list.
>>> list1.append(10)
>>> list1
[1, 2, 3, 10]
>>> list2
[1, 2, 3, 10]
We can also create a copy or clone of the list as a distinct object by three methods. The first method uses slicing, the
second method uses built-in function list() and the third method uses copy() function of python library copy.
Method 1
We can slice our original list and store it into a new
variable as follows:
newList = oldList[:]

Example
>>> list1 = [1,2,3,4,5]
>>> list2 = list1[:]
>>> list2
[1, 2, 3, 4, 5]

Method 2
We can use the built-in function list() as follows:
newList = list(oldList)

Example
>>> list1 = [10,20,30,40]
>>> list2 = list(list1)
>>> list2
[10, 20, 30, 40]
Programs
1.Write a program to create a list using eval() function and print content of the list on the screen.
lst=eval(input("Enter list:"))
print(lst)
output
Enter list: [10,20,30,40,50]
[10, 20, 30, 40, 50]
2.Write a program to create a list of n numbers entered by the user and display the content on the screen.
lst=[]
n=int(input("How many nos u want to create list with:"))
for i in range(0,n):
num=int(input("Enter a number:"))
lst.append(num)
print(lst)
Output
How many nos u want to create list with: 5
Enter a number: 10
Enter a number: 20
Enter a number: 30
Enter a number: 40
Enter a number: 50
[10, 20, 30, 40, 50]
3.Write a program to create a list of numbers and find the maximum element of the list.

lst=[]
size=int(input("Enter size of list:"))
for i in range(0,size):
num=int(input("Enter a no:"))
lst.append(num)
max=lst[0]
for i in range(1,size):
if lst[i]>max:
max=lst[i]
print(max)

output
Enter size of list:5
Enter a no:20
Enter a no:10
Enter a no:70
Enter a no:30
Enter a no:40
70
4.Write a program to create a list of numbers and find the minimum element of the list.

lst=[]
size=int(input("Enter size of list:"))
for i in range(0,size):
num=int(input("Enter a no:"))
lst.append(num)
min=lst[0]
for i in range(1,size):
if lst[i]<min:
min=lst[i]
print(min)

output
Enter size of list:5
Enter a no:20
Enter a no:90
Enter a no:10
Enter a no:30
Enter a no:40
10
5.Write a program to input a list of numbers and search for an number in a list. If a number is found, then print its
location otherwise print an appropriate message if the number is not present in the list.

lst=eval(input("Enter size of list:"))


num=int(input("Enter no to search:"))
size=len(lst)
found=False
loc=0
for i in range(0,size):
if lst[i]==num:
pos=i
found=True
break
if found==False:
print("No not found")
else:
print("No found at position=",pos)

Output
Enter size of list:[35,12,25,50,61]
Enter no to search:50
No found at location= 3
6.Write a program to input a list of numbers and swap elements at the even location with the elements at the odd location
lst=eval(input("Enter size of list:"))
size=len(lst)
for i in range(0,size-1,2):
lst[i],lst[i+1]=lst[i+1],lst[i]
print(lst)

output
Enter size of list:[10,20,30,40,50,60]
[20, 10, 40, 30, 60, 50]

7.Write a program input a list of numbers and reverse this list without creating new list.
lst=eval(input("Enter size of list:"))
size=len(lst)
j=size-1
for i in range(0,size//2):
lst[i],lst[j]=lst[j],lst[i]
j=j-1
print(lst)
output
Enter size of list:[10,20,30,40,50]
[50, 40, 30, 20, 10]
8.Write a program to read a list of n integers (positiveas well as negative). Create two new lists, one having all positive
numbers and the other having all negative numbers from the given list. Print all three lists.

lst=eval(input("Enter size of list:"))


size=len(lst)
plst=[]
nlst=[]
for i in range(0, size):
if lst[i]>0:
plst.append(lst[i])
else:
nlst.append(lst[i])
print("Main List:",lst)
print("Positive no List:",plst)
print("Negative no List:",nlst)

output
Enter size of list:[-8,10,-12,-17,15]
Main List: [-8, 10, -12, -17, 15]
Positive no List: [10, 15]
Negative no List: [-8, -12, -17]
9. Write a program to read a list of elements. Modify this list so that it does not contain any duplicate elements, i.e., all
elements occurring multiple times in the list should appear only once.
lst=eval(input("Enter size of list:"))
newlst=[]
for ele in lst:
if ele not in newlst:
newlst.append(ele)
lst=newlst
print(lst)
output
Enter size of list:[10,20,30,10,40,30,50]
[10, 20, 30, 40, 50]

10.Write a program to read a list of elements and calculate the mean of a list of numbers.
lst=eval(input("Enter size of list:"))
size=len(lst)
sum=0
for i in range(0,size):
sum=sum+lst[i]
mean=sum/size
print("Mean=",mean)
output
Enter size of list:[10,20,30]
Mean= 20.0

You might also like