List Manipulation

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

IP notes

Ln. 7- List Manipulation


INTRODUCTION
A list is a standard data type of Python that can store a sequence of values belonging to any type.
It is a collection which is ordered and changeable.
They are written with square brackets.
The most powerful thing is that list need not be always homogeneous.
A single list can contain strings, integers, as well as objects.
Lists are mutable (i.e. modifiable) , you can change elements of a list in a place. In other words,
the memory address of a list will not change even after you change its values.

Declaring a list
To create a list, put the list elements in square brackets.
Indexing in a list begins from 0
Firstlist = ["France", "Belgium", "England"]
print(Firstlist)
Examples of list-
[ ] # list with no member, empty list
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ] # list of integers
list3 = ["a", "b", "c", "d"]

Empty list
• The empty list is [ ]. It is equivalent of 0 or ‘ ‘.
• You can also create an empty list as : L = list( )
• [ ] # list with no member, empty list

Changing Content of a list


Firstlist = ["France", "Belgium", "England"]
Firstlist[2]=“Russia”
This statement will replace England by Russia

Working with list


• To access values in lists, use the square brackets along with index whose value is to be displayed .
e.g: print (list1[0] )

Nested list
A list can have an element in it, which itself is a list. Such a list is called nested list.
e.g. L1 = [3, 4 , [5,6], 7]

Creating list from existing sequence


A list from a given sequence(strings, tuples and lists) can be created as per following syntax:
L = list(<sequence>)
eval function
The eval() function evaluates the specified expression, and if the expression is a legal Python
statement, it will be executed.
It returns the result evaluated from the expression.
It tries to identify the type by looking at the given expression.
x = 'print(55)'
Output - 55
eval(x)

x=1
eval('x + 1') Output - 2

Accessing Individual Elements


The individual elements of a list are accessed through their indexes.
If you give index value outside the legal indices ( 0 to length-1 or –length to -1), Python will raise
Index Error.
Example-
Vowels = [‘a’,’e’,’i’,’o’,’u’]
Vowels[0]  ‘a’
Vowels[-5]  ‘a’
Vowels [5]  Error- list index out of range

Difference- String & Lists


Lists can any type of data i.e. integers, characters, strings etc, while strings can only hold a set of
characters.
Strings are not mutable, while lists are mutable. You cannot change individual elements of a
string in place, but Lists allow you to do so.

Traversing a List
Traversal means accessing and processing each element of it.
The for loop makes it easy to traverse or loop over the items in a list, as per following syntax:
for <item> in <list> : p
L=[‘p’,’y’,’t’,’h’,’o’,’n’] y
for a in L: t
print (a) h
o
n
Traversing a List using index value
L = [ ‘q’ , ‘w’ , ‘e’ , ‘r’ , ‘t’ , ‘y’ ] Value at index o is q
Length = len(L) Value at index 1 is w
for a in range(length) : Value at index 2 is e
print(“value at index”, a, “is”, L[a]) Value at index 3 is r
Output produced by above code: Value at index 4 is t
Value at index 5 is y
Comparing Lists
Comparison between lists can be done using standard comparison operators of Python, i.e. < , > ,
== , != etc.
For 2 lists to be equal, they must have the same number of elements and matching values.
In the case of int and float, they will be equal if they have the same matching values not
considering the decimal point.
Example-
L1=[1,2,3]
L2 =[1,2,3]
L3=[4,5,6]
L4=[‘a’,’b’,’c’]
L1==L2  True
L1==L3  False
L1==L4  False

Non equality comparison in list sequences

List operations
Joining Lists
The concatenation operator + , when used with two lists, joins two lists.
The resultant list displays the elements of the 1st list followed by that of the 2nd.
Eg:-
A= [ 1,3,5]
B= [ 6,7,8]
A+B O / p  [ 1,3,5,6,7,8]
Note- Both the operands must of list types. The following expressions can result into an error-
List + number , List + string

Repeating or Replicating Lists


Operator is used to replicate a list specified number of times.
A=[1,2,3]
A*2 O/p – [1,2,3,1,2,3]

Slicing the Lists


List Slices are the sub part of a list extracted out.
You can use indexes of list elements to create list slices as per following format:
seq = L [start : stop ]
The above statement will create a list slice namely seq having elements of list L on indexes start,
start+1 , start+2,…….,stop-1.

>>> a=[10,12,14,20,22,24,30,32,34]
>>> b=a[0:2]
>>> b O/p - [10, 12]
>>> b=a[0:-1]
>>> b O/p - [10, 12, 14, 20, 22, 24, 30, 32]
>>> b=a[3:-3]
>>> b O/p - [20, 22, 24]
>>> b=a[3:3]
>>> b [] --even if both limits are out of bounds, Python will not give any error and returns an
empty sequence.
a=[20,22,24]
>>> a[1]=28
>>> a O/p - [20, 28, 24]
b=a[2:30]
>>> b O/p - [24]
a=[10,12,14,20,22,24,30,32,34]
>>> b=a[-12:6]
>>> b O/p - [10, 12, 14, 20, 22, 24]

List also support slice steps. That is, if you want to extract, not consecutive but every other element of
the list, there is a way out – the slice steps. The slice steps are used as per following format:
seq = L[start : stop : step]

Example-
a=[10,12,14,20,22,24,30,32,34]
a[0:10:2] O/p - [10,14,22,30,34]
a[2:10:3] O/p - [14,24,34]
a[: : 3] O/p - [10,20,30]

Reversing a List
Abc = [5 ,6, 8, 11, 3]
Abc [ : : -1] Output- [3, 11, 8, 6, 5]

Using Slices for list modification


Abc = [“one”, “two”, “THREE”]
Abc[0:2] = [0,1] Output- [0, 1, “THREE”]
>>> A=[1,2,3,4,5,6]
>>> A[0:3]="c"
>>> A Output - ['c', 4, 5, 6]

Built in Functions
Python offers various built in functions to perform different operations on lists
• APPEND  List.append(elem)
• INSERT  List.insert(index,elem)
• EXTEND  List.extend(list 2)
• INDEX  List.index(elem)
• REMOVE  List.remove(elem)
• SORT  List.sort( )
• REVERSE  List.reverse( )

APPEND
It adds a single item to the end of the list. It doesn’t create a new list but modifies the original one.
Syntax is- List.append(item)
e.g : abc= ["apple", "banana", "cherry"]
abc.append(“plum")

PROGRAM
Create a list of items. Accept a new value to be added to the list. If the number is even then add it to
the list and display the sum of all the values. If the number is odd, then just display the message
“Enter an even number to find the sum”
a = [10,20,30,40]
b=int(input("Enter new value to be added : "))
a.append(b)
print("New list is : " , a)
if b%2==0:
sum = 0
for num in a:
sum=sum+num
print("Sum of the values = ",sum)
else:
print("Enter an even number to find the sum!!!!!!!!!!")

EXTEND
• The extend( ) method adds one list at the end of the other list.
• All the items of the list are added at the end of an already created list.
• It cannot add a single element; it requires a list to be added.
Syntax is- List.extend(list2)
Eg:- A=[5,3,2,6]
B = [10,11]
A.extend(B)
print (A) O/p- [5,3,2,6,10,11]

INSERT
• The insert( ) function inserts an item at a given index.
• It is used as per following syntax:
List.insert(index_number, value)
• Takes two arguments – index of the item to be inserted and the item itself.
T1 = [‘a’,’e’,’u’]
T1.insert(2,’’I’)
T1  O/p - [‘a’,’e’,’I’,’u’]

• If however, index is less than zero and not equal to any of the valid negative indexes of the list, the
object is prepended, i.e. added in the beginning of list.
• T1= [‘a’, ’e’, ’i’ , ‘o’ , ‘u’]
• T1.insert (-9, ‘k’)
• T1 O/p - [‘k’, ‘a’, ’e’, ’i’ , ‘o’ , ‘u’]

REVERSE
• This function reverses the order of the elements in a list.
• It does not create a new list but replaces a new value in place of the already existing items.
T1= [‘abc’ , ‘def’ , ‘ghi’ ]
T1.reverse ( )
T1 O/p- [‘ghi’ , ‘def’ , ‘abc’]

INDEX
• This function returns the index of first matched item from the list.
• Syntax - List.index (<item>)
• If the item is not in the list, an error is raised.
X = [12,14,15,17,18]
X.index(15) O/p- 2
X = ‘Python’
X.index(‘h’) O/p- 3

UPDATE
• Lists are mutable; we can assign new values to existing values.
• Assignment operator = is used to change an item or a range of items.
X = [12,14,15,17,18]
X[1] = 4 O/p- [12,4,15,17,18]
LEN
• Len() function returns the length of the list.
A = [6,’abc’,10,’new’]
print (len(A)) O/p- 4

SORT
• It sorts the items of the list in ascending or descending order.
• For strings, sorting is done on the basis of their ASCII values.
• To sort it in the decreasing order use, sort(reverse=True)
a=[10,4,8,20,100,65]
>>> a.sort()
>>> a O/p - [4, 8, 10, 20, 65, 100]
>>> a.sort(reverse=True)
>>> a O/p - [100, 65, 20, 10, 8, 4]

CLEAR
• It removes all the items from the list. It doesn’t take any parameters.
• It only empties the given list and does not return any value.
a=[10,4,8,20,100,65]
>>> a.clear()
>>> a O/ p - [ ]

COUNT
• This function counts how many times an element has occurred in a list.
• If the given item is not in the list, it returns zero.
• It is used as per following format: List.count(<item>)
a=[10,4,8,20,100,65]
>>> a.count(4) O/p - 4

DELETION OPERATION
• To delete or remove items from a list, there are many methods used-
Pop() or del () is used in cases the index is known.
Remove() is used if the element is known.
Del() with list slice is used to remove more than one element.

POP
• The pop() method removes the element from the specified index and returns the element which
was removed.
• An error is shown if the list is already empty.
List.pop(<index>) # index is optional; if skipped, last element is deleted.
X=[1,2,5,4,3,6,7,12,50]
>>> Y=X.pop(2)
>>> X O/p - [1, 2, 4, 3, 6, 7, 12, 50]
>>> Y 5
>>> X O/p - [1, 2, 4, 3, 6, 7, 12, 50]
>>> X.pop()
50
>>> X O/p - [1, 2, 4, 3, 6, 7, 12]

DEL
• It removes the specified element from the list but does not return the deleted value.
• An error is shown if an out of range index is specified with del() and pop().
>>> X [1, 2, 4, 3, 6, 7, 12]
>>> del X[5]
>>> X [1, 2, 4,3, 6, 12]
>>> X [1, 2, 4, 6, 7, 12]
>>> del X[-2]
>>> X [1, 2, 4, 6, 12]

DEL with slicing


• It removes the specified elements from the list identified with the slice operator but does not
return the deleted value.
• If you use del <Listname> only, then it deletes all the elements and the list object too.
>>>P=[10,20,30,40,50,60,70,80,90]
>>> del P[2:4]
>>> P O/p - [10, 20, 50, 60, 70, 80, 90]
>>> del P
>>> P O/p - Error name 'P' is not defined

REMOVE
• An element can be removed from the list using remove method.
• It is used when we know the element to be removed and not the index.
Eg: pqr= ["apple", "banana", "cherry"]
pqr.remove(“cherry”)

Program - # To display all the even and odd numbers from a list.
A=eval(input("Enter list: "))
print("Odd numbers- ")
for num in list1:
if num % 2 != 0:
print(num, end = " ")
print("\n")
print("Even numbers- ")
for num in list1:
if num % 2 == 0:
print(num, end = " ")

MAX - It returns the element with the maximum value from the list.
P=[10,20,30,40] max(P) O/p- 40
Q=[‘A’,’a’,’B’,’C’] Max(Q) O/p  a Highest ASCII value
Q=[‘apple’,’bus’,’shell’]
Max(Q) O/p -shell  Returns the string that starts with the character with highest ASCII value

MIN - It returns the element with the minimum value from the list.
P=[10,20,30,40] min(P) O/p - 10
If there are 2 or more strings that start with the same character, then the second character is
compared and so on.

Program - # Count the number of occurrences of an item in a list


A=eval(input("Enter list: "))
num=eval(input("Enter the number:"))
count=0
for i in A:
if num==i:
count+=1
if count==0:
print("Item is not in list")
else:
print("Count of item - ",count)
# To find the sum and average (mean) of a list of items
list1 = eval(input("Enter list: "))
sum = 0
for num in list1:
sum = sum +num
average = sum / len(list1)
print ("sum of list element is : ", sum)
print ("Average of list element is ", average )

Find the output of


PQ = [“Mon”,45,”Tue”, 43,”Wed”,42]
print(PQ [ 1:-1]) [45, 'Tue', 43, 'Wed']
PQ [0:2] = ‘Z’ ['Z', 'Tue', 43, 'Wed', 42]
print (PQ)

a=[5,10,15,20,25]
k=1
i=a[1]+1
j=a[2]+1 [11 16 15]
m=a[k+1]
print(i,j,m)

str1=‘book’
print(list(str1) ['b', 'o', 'o', 'k']

L=['p','w','r','d','a']
L.remove('r') ['p', 'w', 'd', 'a']
print(L) a
print(L.pop()) ['p', 'd']
del L[1]
print(L)

L1=[500,600]
L2=[35,45]
L1.append(700)
L1.extend(L2) [500, 600, 700, 35, 45, 2]
L1.insert(25,2) [500, 600, 700, 35, 45, 2, 35, 45]
print(L1) [500, 600, 700, 35, 45, 2]
print(L1+L2) 3
print(L1) [35, 45, 35, 45]
print(L1.index(35))
print(L2*2)

What is the for loop for the following output?


1 5
4 for A in range(1,11,3): 4 for B in range(5,0,-1):
7 print(A) 3 print(B)
10 2
1
1 2
3 for C in range(1,8,2): 4 for D in range(2,11,2):
5 print(C) 6 print(D)
7 8
10
Program-
To enter a string and count the number of words
A=input("Enter a string :")
B=A.split()
count=0
for i in range(len(B)):
count+=1
print("Number of words : ", count)
Enter a string :The sun rises in the east
Number of words : 6

#To display square if the element is an integer and to change case if it is a string
L=[10,"FUN",40,"FEW",50,"FULL"]
for i in range (len(L)):
if type(L[i])==int:
L[i]=L[i]**2
elif type(L[i]) ==str:
L[i]=(L[i]).swapcase()
print(L)
[100, 'fun', 1600, 'few', 2500, 'full']

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy