CH - 11 LIST MANIPULATION
CH - 11 LIST MANIPULATION
TOPICS
INTRODUCTION
Lists:
In Python a List is a linear data structure, which stores different types of data or
elements in linear order.
Advantages of List:
It support mutability.
It is dynamic.
It is multi-dimensional.
DIFFERENCE BETWEEN LISTS AND STRINGS
i. The Lists are mutable sequences while strings are immutable.
ii. In consecutive locations, strings store the individual characters while list stores
the references of its elements.
iii. String store single type of elements (i.e. all are in character form) while lists can
store elements belonging to different types.
CREATING LIST IN PYTHON
In Python List can be created using Square Bracket [ ].
(or)
Example:
To create a list with some values, we must use the following syntax:
Syntax:
Variable_name= [value1,value2,value3…]
Examples:
(v) S=[10,20,"Raja“,164.5,'M‘]
NESTED LIST CREATION
Nested List:
Example:
(ii) N=[10,20,30,[40,50],60,70,[80,90,100]]
For Example:
L1=[10,20,33,44] 10 20 33 44
0 1 2 3
-5 -4 -3 -2 -1
L2=[1,2,[30,45],50,60] 1 2 50 60
0 1 2 3 4
Syntax:
List_variable_name[index]
Example:
2. Create a List Fruits with values Mango, Orange, Apple, Grapes, Pineapple and write
suitable statements to do the following operations:
The for loop makes, easy to traverse or loop over the items in the list.
(or)
Note: In the 2nd syntax len() is used to calculate total number of elements present in
the list.
EXAMPLE FOR TRAVERSING LIST ELEMENTS
Example -1:
Sample Output
(or):
SEARCHING ELEMENT IN A LIST
Searching is a process of finding particular element from a list of elements.
In simple, searching is exactly same as traversing list elements with search condition
till end. This technique is called "Linear Search".
Example:
Run- 1:
Run- 2:
EXAMPLE PROGRAM USING LISTS
1. Write a Program to find minimum element from a list of element in the list.
Run- 1:
EXAMPLE PROGRAM USING LISTS
2. Write a Program to count frequency of a given element in a list of numbers.
Run- 1:
EXAMPLE PROGRAM USING LISTS
3. Write a Program to calculate mean of a given list of numbers.
Run- 1:
SLICING THE LIST
Slicing:
List slice refers to a part of the List, where List are sliced using a range of indices.
(or)
Slicing is an operation that can be performed on the sequence to get part of the
sequence.
Syntax: Variable_Name[start:end:step]
Where,
Start -> It is starting index from where we want to start the extraction.
Step -> It is the increment/decrement value which specifies next index to be extracted.
Further we way use the above general syntax in different ways to slice the strings:
vi. List[:] Extract the entire List 0th index to till last index.
vii. List[ : : step] This will print alternative element according to step size.
Note:
In the above syntax start value is included and end value is excluded.
LIST SLICING EXAMPLES
INTERESTING INFERENCE IN LIST
SLICING
Giving upper limit way beyond the size of the list. But,
Python return elements from list falling in range 3
onwards <30.
2. Write a Python program to create a list of marks of five subjects of a student and print
on screen.
We cannot concatenate List with any other type. I.e. we can concatenate List with
List only.
(i) in: It returns True if a elements exist in the given List. Otherwise it
returns False.
(ii) not in: It returns True if a element does not exist in the given List.
Otherwise it returns False.
Example:
(iv) COMPARISON OPERATORS
In Python, all relational operators (<, >, <=, >=, = =, !=)
When applying comparison operators on list, two sequences must be in same type.
Example:
LIST MODIFICATION/UPDATAION
In Python, Lists are Mutable(i.e. Changeable).
Syntax:
Example - 1:
Note: During Modification of List, Python never creates new list. I.e. It modifies
elements of the list in same memory.
Using Slices for List Modification:
Example:
Note: If we want to modify list elements, the values being assigned must be sequence.
Example -1 :
Example -2:
If we give a list slice with range much outside the length of the list, it will simply add
the values at the end of the list.
Example:
If we give a list slice with lower limit , it will simply add the values at the elements at
starting index of the list.
DELETING LIST ELEMENTS
Like modification, Python will allow to delete the elements of the list.
We can delete entire list object from memory or we can delete only specific elements
from list object.
Example:
LIST FUNCTIONS AND METHODS
• List Functions and Methods are used to manipulate the List.
v. List.index()
vi. List.append()
vii. List.extend()
viii. List.insert()
ix. List.pop()
x. List.remove()
xi. List.clear()
xii. List.count()
xiii. List.reverse()
xiv. List.sort()
(i) len():
Syntax:
• len(List_variable_name)
EX:
>>>L=[10,20,30,"Raja",40]
>>>len(L)
>>> L=[10,20,[30,40,50],60,70]
>>>len(L)
5
(ii) List.index():
• This method returns the index of first matched item from the list.
• If the given item is not in the list, it raises exception Value Error.
• Syntax: List.index(<item>)
Example:
(iii) min():
• If the list contains different type of values or if list contains nest list then it will show
error message.
• Syntax: min(List_Variable_Name)
Example:
(iv) max():
• If the list contains different type of values or if list contains nest list then it will show
error message.
• Syntax: max(List_Variable_Name)
Example:
(v) sum():
• If the list contains different type of values or if list contains nest list then it will show
error message.
• Syntax: sum(List_Variable_Name)
Example:
(vi) List.index():
• This method returns the index of first matched item from the list.
• If the given item is not in the list, it raises exception Value Error.
• Syntax: List.index(<item>)
Example:
(vii) List.append():
• This method is used to add an item or value to the end of the list.
Ex:2 Ex : 4
Ex:3
Ex 1
(viii) List.extend():
• The extend() can add multiple elements from a list supplied to it as arguments.
• Syntax: List.extend(existing_list_variable)
Ex:
Difference between L.append() and L.extend()
List.append( ) List.extend()
ii. Ex: >>>L=['a', 'b', 'c'] ii. Ex: >>>L=['a', 'b', 'c']
>>>L.append(‘d’) >>>R=['d', 'e', 'f']
>>>print(L) >>>L.extend(R)
>>>print(L)
Output: ['a', 'b', 'c', 'd'] Output: ['a', 'b', 'c', 'd', 'e', 'f']
(ix) List.insert():
Ex 1:
Ex:2
(x) List.pop():
• The pop() is used to remove the item from the list based on the given index and it
returns immediately removed element. If it is out of index then, it will show an error
message.
• Syntax: List.pop(index)
• If index value is not given in pop(), then by default it removes last element of the list.
Example:
(xi) List.remove():
• Syntax: List.remove(element/value)
• If given element is not available in list, then Python will raise ValueError.
Ex 1:
(xii) List.clear():
• The clear() is used to remove all the items from the list. The list becomes empty list
after this function.
• Syntax: List.clear()
Ex 1: Note:
After using List.clear() the list object still
exist on the Memory. I.e it will delete only
elements of the list , not an memory.
(xiii) List.reverse():
• Syntax: List.reverse()
Ex 1:
(xiv) List.sort():
• The sort() is used to sorts the list, by default increasing order(Ascending Order).
Ex 1:
Ex 2:
Ex 3:
Making true of Copy of List
• Assignment with an assignment operator on list does not make a copy. Instead,
assignment makes the two variables point to the one list in memory. (Shallow copy)
• Example:
>>> a=['red’,’green’,’blue’]
>>>b=a
>>>print(b)
['red’,’green’,’blue’]
>>>b.append(‘yellow’)
>>> print(b)
['red’,’green’,’blue’,’yellow’]
>>>print(a)
['red’,’green’,’blue’,’yellow’]
PRACTICE QUESTIONS
1. What is meant by list?
2. Compare list with string. How they are similar and how they are different?
3. Can you change the element of a sequence? What if the sequence is a string? What if the sequence
is a list?
8. Start with the list [8,9,10]. Do the following using list functions:
(a) Set the second entry(i.e. index 1) to 17. (b) Add 4,5 and 6 to the end of the list.
(c) Remove the first entry from the list. (d) Sort the list.
10. What are list slices? What for can you use them?
11. An index out of bounds given with a list name causes error, but not with list slices. Why?
12. What is the difference between following two expressions, if L is given as [1,3,5]
(a) L1==L2 (b) L1.upper( ) (c) L1[3].upper( ) (d) L2.upper( ) (e) L2[1].upper( )
(f) L2[1][1].upper( )
PRACTICE QUESTIONS
Q.No 1
How do you create the following lists?
(a) [4,5,6]
(b) [-2,1,3]
(c) [-9,-8,-7,-6,-5]
(d) [-9,-10,-11,-12]
(e) [0,1,2]
Q.No 2:
If a = [5,4,3,2,1,0] evaluate the following expressions: Sol:
>>>L[3:4][0][1] 'words'
>>>L[3:4][0][1][2] 'r'
What does each of the following expressions evaluate to? Suppose that L is the List.
Write the most appropriate list method to perform the following tasks.
Given a List:
Output:
Output:
PRACTICE QUESTIONS
Q.No 7:
Output:
Output:
PRACTICE QUESTIONS
Q.No 8:
Output:
Output:
PRACTICE QUESTIONS
Q.No 9:
print(S+2)
III.
print(L[ : : -1]
print(L[-1 : -2 : -3 : -4])
THE END