0% found this document useful (0 votes)
7 views

CH - 11 LIST MANIPULATION

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)
7 views

CH - 11 LIST MANIPULATION

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/ 58

CHAPTER - 11

LIST MANIPUL ATION

TOPICS
INTRODUCTION
Lists:

 In Python a List is a linear data structure, which stores different types of data or
elements in linear order.

 Each data or element of a List is called "Items“.

 In Python List is dynamic.

Advantages of List:

 It support mutability.

 It is used to store large amount of different types of data in single memory.

 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 [ ].

 Every Item or element has index that ranges from 0 to n-1.

To create an Empty List:

 An empty list can be create by two ways. They are:

(i) By Assigning Empty Square bracket [ ] to a variable.

(or)

(ii) By Assigning list( ) method to a variable.

Example:

A=[ ] (or) M= list( )


CREATING LIST IN PYTHON
(ii) Create List with values:

 To create a list with some values, we must use the following syntax:

Syntax:

Variable_name= [value1,value2,value3…]

Examples:

(i) L=[ ] # Empty List

(ii) M=[10,20,30,45,56] # List of Integers.

(iii) N=[10,20,30,45.5,78.56,67,79.4] # List of Integers and floating point number.

(iv) ch=['a', 'e', 'i', 'o', 'u'] # List of characters.

(v) S=[10,20,"Raja“,164.5,'M‘]
NESTED LIST CREATION
Nested List:

 If a list have another list inside of it then it is called "Nested List".

 Nested lists are used to create 2-D / Multi dimensional list.

Example:

(i) Fruits=['Apple',['Red','Green'], 'Grapes', 'Orange‘]

(ii) N=[10,20,30,[40,50],60,70,[80,90,100]]

(iii) V=['a',['b',['c', 'd‘], 'e', 'f‘], 'g‘, 'h']


MEMORY REPRESNTATION OF LIST & NESTED LIST
 Each element or an item of an tuple is stored in contagious memory location(one after
other). Each item has its own positive & negative indices.

 For Example:

Consider the following tuple -4 -3 -2 -1

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

[2] (or) [-3] = 30 45


[0] [1]
ACCESSING ELEMENTS OF A LIST
 A list elements can be accessed in two ways they are:

(i) Accessing individual elements of a list.

(ii) Accessing elements through loops.


(i) ACCESSING INDIVIDUAL ELEMENTS OF A LIST
 The individual elements of a list are accessed through their indices.

 We can access elements of a list either from forward or backward.

 Because, List supports Forward index as well as backward index.

Syntax:

List_variable_name[index]

Example:

Accessing Nested elements


PRACTICE QUESTION - 1
1. Create a List Sports with values Cricket, Hockey, Tennis, Football, Kho kho. Print the
value of first element?

2. Create a List Fruits with values Mango, Orange, Apple, Grapes, Pineapple and write
suitable statements to do the following operations:

(i) Print the value of 3rd element from the beginning .

(ii) Print the value of 2nd element from Back.

(iii) To Print Pineapple.


(ii) TRAVERSING LIST ELEMENTS
 Traversing a list means, process or go through each element of a list sequentially.

 We can traverse a list using two types of loops. They are:

(i) Traversing a list elements using while loop.

(ii) Traversing a list elements using for loop.

 The for loop makes, easy to traverse or loop over the items in the list.

Syntax Traversing through for loop:

(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:

 Slicing means "a part of“

 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.

How to apply Slicing in List?

Syntax: Variable_Name[start:end:step]

Where,

Start -> It is starting index from where we want to start the extraction.

end ->It is the index upto which we want 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:

i. List[Start:end] Extract elements from start to end -1.

ii. List[Start:] Extract elements from start to end.


iii. List[:end] Extract elements from 0 th index to end-1

iv. List[-Start:] Extract elements from start to end-1

v. List[:-end] Extract elements from 0th index to end-1

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.

Giving lower limit much lower, But, Python return


elements from list falling in range -15 onwards <4

Giving one limit is out of bound, But, Python return


elements from list falling in range 6 onwards <10

Python gives no error and returns an empty sequence


as no element of S has index falling in range of 10 to
20.
PRACTICE QUESTION - 2
1. How are lists different from strings when both are sequences?

2. Write a Python program to create a list of marks of five subjects of a student and print
on screen.

3. Write a Python program to reverse the list.

4. Write a Python program to sum of all the elements in the list.

5. Write a Python program to print only even numbers from list.


LIST OPERATIONS
 List operations are used to manipulate the list.

 The following operators are support by List manipulation:

(i) Concatenate operator.

(ii) Replication operator.

(iii) Membership operators.

(iv) Comparison operators.


(i) Joining List or Concatenate operator
 Joining of two or more List operands is called "Concatenation".

 The '+‘(plus) operator is used to concatenate Lists in python.

 We cannot concatenate List with any other type. I.e. we can concatenate List with
List only.

Some Valid Examples: Some Invalid Examples:


(ii) Replication operator
 This is used to repeat the List 'n‘ number of times. It is also known as
“Repetition operator".

 To repeat a List in Python, '*‘ (multiplication) operator is used.

 Syntax: List * Number (or) Number * List

Some valid Examples: Some Invalid Examples:


(iii) MEMBERSHIP OPERATORS
 In Python ‘in’ and ‘not in’ operators are called membership operators.

Working Method of in and not in operators:

(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 (<, >, <=, >=, = =, !=)

 It will compare the elements of the list in lexicographical order.

 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).

 List modifications means, changing individual elements of the list.

Syntax:

List_variablename[index]=New element or value

Example - 1:

Example – 2: Modification in Nested List.

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:

 We can also use slicing to modify elements of List.

Example:

Note: If we want to modify list elements, the values being assigned must be sequence.

Example -1 :

 But, During modification if we assign non-sequence values to list slice such as a


number, Python will give an error.

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.

 We can achieve this by using del keyword.

 Syntax: del list_variable_name (or) del list_variable_name[index]

 Example:
LIST FUNCTIONS AND METHODS
• List Functions and Methods are used to manipulate the List.

• The following are some of the List Functions and Methods.

i. len( ) ii. min( ) iii. max( ) iv. sum( )

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():

• This function is used to find length of the list.

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():

• This function returns the minimum/smallest element of the list.

• 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():

• This function returns the maximum/biggest element of the list.

• 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():

• This function returns the sum of the element of the list.

• 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()

i. It is used to add one element to i. It is used to add Multiple


a list at a time. elements to a list at a time by
passing another list or tuple or
string as argument.

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():

• The insert() is used to insert a element/value in between or in particular


position(index).

• Syntax: List.insert(index, value)

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():

• The remove() is used to removes the first occurrence of a given element .

• 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():

• The reverse() is used to reverse the order of elements in place.

• Syntax: List.reverse()

Ex 1:
(xiv) List.sort():

• The sort() is used to sorts the list, by default increasing order(Ascending Order).

• Syntax: List.sort() (or) List.sort(reverse=True/False) -> (reverse is optional)

• If reverse value is True it will sort in Descending order.

• If reverse value is False it will sort in 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?

4. What is the difference between append() and insert() methods of list?

5. What is the difference between pop() and remove() methods of list?

6. How does sort() works? Give example.

7. What does list.clear() function do?

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.

(e) Double the list. (f) Insert 25 at index 3.


PRACTICE QUESTIONS
9. What is the purpose of del operator and pop method?

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]

(i) >>> L*3 (ii) >>> L*=3

13. Given two lists:

>>> L1=["this", 'is', 'a', 'list']

>>> L2=["this", ["is", "another"], "List"]

Which of the following expressions will cause an error and why?

(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:

(a) >>> a[0] (a) 5


(b) >>>a[-1] (b) 0
(c) >>>a[a[0]] (c) 0
(d) >>>a[a[-1]] (d) 5
(e) >>>a[a[a[a[2]+1]]] (e) 1
PRACTICE QUESTIONS
Q.No 3:

What does each of the following expression evaluate to?

(a) >>>L[3:4] [['few', 'words']]

>>>L[3:4][0] ['few', 'words']

>>>L[3:4][0][1] 'words'

>>>L[3:4][0][1][2] 'r'

(b) >>> "few" in L False

(c) >>> "few“ in L[3] True

(d) >>> L[4:] ['that', 'we', 'will', 'use']


(e) >>> L[0 : :2] ['These', 'a', 'that', 'will']
(f) >>>[ L [1] ] +L[3] ['are', 'few', 'words']
PRACTICE QUESTION
Q.No 3:

What does each of the following expressions evaluate to? Suppose that L is the List.

(a) >>> len(L) 7

(b) >>> L[3:4] + L[1:2] ['that', ['are', 'a']]

(c) >>>"few" in L False

(d) >>>"few“ in L[2:3][0] True

(e) >>>"few“ in L[2] True

(f) >>>L[2][1:] False

(g) >>>L[1]+L[2] ['are', 'a', 'few', 'words']


PRACTICE QUESTIONS
Q.No 4:

Write the most appropriate list method to perform the following tasks.

(a) Delete the given element from the list. List.remove()


(b) Delete the 3rd element from the list. List.pop()
(c) Add an element in the end of the list. List.append()
(d) Add an element of the beginning of the list. List.insert()
(e) Add elements of a list at the end of the list. List.extend()
PRACTICE QUESTIONS
Q.No 5:

Given a List:

(a) Which list slice will give will return

(b) Which expression will return

(c) Which list slice will return

(d) Which list slice will return


PRACTICE QUESTIONS
Q.No 6:

Predict the output of the following codes:

Output:
Output:
PRACTICE QUESTIONS
Q.No 7:

Predict the output of the following codes:

Output:
Output:
PRACTICE QUESTIONS
Q.No 8:

Predict the output of the following codes:

Output:
Output:
PRACTICE QUESTIONS
Q.No 9:

I. Find the error(s) in the following codes: II.

(i) >>> L1=[1,11,21,31] (a) L1=[1,11,21,32]

(ii) >>> L2=L1+2 S=L1.remove(41)

(iii) >>> L3=L1*2 (b) L1=[1,11,21,23]

(iv) >>> S= L1.index(45) S=L1.remove(31)

print(S+2)

III.

L=[3, 3, 8, 1, 3, 0, '1', '0', '2', 'e', 'w', 'e' ,'r']

print(L[ : : -1]

print( L[-1 : -2 : -3])

print(L[-1 : -2 : -3 : -4])
THE END

You might also like