Xi I.P. of CH - List
Xi I.P. of CH - List
Chapter : List
6.1 INTRODUCTION
Sequences arise naturally in many real-life situations. A year has 12 months (January,
February, March, April, May, June, July, August, September, October, November and
December). The months of the year are in a sequence. After January, it will always be February.
It is impossible to jump from March to July because it has to go in a sequence. So, we say a
Sequence is an object that contains multiple items of data. The items are stored in a sequence
one after the other such as a sequence of events, movements, items, or a sequence in which a
player records (music) with a sound recorder/sequencer. Consider the example of a sequence
of cars as shown in Figure.
As is evident from the above figure, there is a sequence of cars and each car becomes an
element/item of this particular sequence. Here, we have a grey-coloured car, a blue car, a red
car and so on.
So, all of these cars combined together form a sequence. Python also supports sequence which
can be considered as containers and in those containers certain items are stored. A sequence
may have repeated items in the list. The number of elements is called the length of the sequence.
The various sequences available in Python are shown in Figure below.
2. LISTS
A list is a collection of values or an ordered sequence of values/items.
The items in a list can be of any type such as string, integers, float, objects, or even a
list.
Elements of a list are enclosed in square brackets [ ], separated by commas.
Lists are mutable, i.e., values in the list can be modified, which means that Python will
not create a new list when you make changes to an element of a list.
The values that make up a list are called its elements. Elements in a list need not be of
the same type. In other words, we say that lists are heterogeneous (of multiple types) in
nature.
Like a string (sequence of characters), list also is a sequenced data type.
1. Declaring/Creating List
Lists can be created by putting comma-separated values/items within square brackets--
square brackets indicate the start and end of the list, consisting of elements separated
by a comma. The syntax for creating a list is:
<list name> = []
For example,
L = []
This construct is termed as a "List Display Construct". Square brackets in the above
syntax contain the set of values/elements constituting the list with the name given as
<list_name>.
This is termed as initialization of the list with a blank or no values or we can say an
empty list.
A list can be populated with any type of values/collection of items by enclosing inside
square brackets [].
For example,
In the above example, we have a list of fruits having three items-Mango, Apple and Grapes,
separated by comma and enclosed inside square [ ] brackets.
For example,
Consider list1 containing 10 elements.
List1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
This list in computer memory shall be represented as shown in Figure below:
Each element of the above list can be accessed through their indexes enclosed inside square
brackets.
Consider another list with elements, 'C','o','m','p','u','t','e','r' stored inside memory as shown:
An IndexError appears if you try and access element that does not exist in the list. It
will display the error message as: IndexError: list index out of range
Now, in the above code, we are trying to access eighth element (>>>list[8]) from the list which
does not exist as we are having a total of 8 elements for which the last index is 7. Since we are
trying to access the element at index 8, Python will give an "IndexError".
Similarly, if we try to concatenate a list with string value, it will again generate Type Error.
Thus, we conclude that the '+' operator, when used with lists, requires both the operands to
be of list types.
6.3.2 REPETITION/REPLICATION
Multiply (* asterisk) operator replicates the List for a specified number of times and creates a
new list.
However, we cannot multiply one list with another as shown in figure below.
3. MEMBERSHIPTESTING
For example,
To display the names of students who are members of class XII.
4. INDEXING
Index is nothing but there is an index value for each item present in the sequence. So,
you have 0th index, 1st index, 2nd index, 3rd index, and so on, depending upon the
sequence that you have.
In Python, indexing starts from 0 like other programming languages.
As shown in the example of sequence of cars in figure below, we have 8 items in this
particular sequence and the index range is from 0 to 7.
Thus, lists in Python can have/store different types of elements stored in a particular
sequence such as integers, strings, etc.
Indexing and slicing are two inter-related operations in lists. Slicing is done through
indexing.
Slicing is an operation in which we can slice a particular range from that sequence.
List slices are sub-parts of a list extracted out. List slices can be created through the use
of indexes.
Slicing is used to retrieve a subset of values. A slice of a list is basically its sub-list.
While indexing is used to obtain individual items, slicing allows us to obtain a subset
of items.
When we enter a range that we want to extract , it is called range slicing.
The syntax used for slicing is:
Syntax:
list[start:stop:step]
where, start is the starting point; stop is the stopping point, which is not included; and
step is the step size-also known as stride-and is optional. Its default value is 1.
Let us consider a list, 'list1', with the following values and results after slicing operation:
As shown above, the slice extracted from list1 is stored in the variable, slice1. The list
slice is a list in itself, i.e., we can perform all operations on it just like we perform on
lists.
Thus, when we try to modify the list slice, slice1, it is successfully implemented since
the list slice, slice1, is a list in itself.
The slicing operation is entirely based on indexing.
In case the resulting index lies outside the list, Python raises an Indentation Error.
Slice range (start and stop argument) is treated as boundary, and the result will simply
contain all the elements which lie between the boundary.
In case the start and stop limits lie outside the boundary, Python still returns the
elements that lie between the specified range/boundary without raising any error.
6.4 NESTED LISTS
When a list appears as an element of another list, it is called a nested list.
To access the element of nested list of list1, we have to specify two indices listl [i] [j].
The first index i will take us to the desired nested list and the second index j will take us tothe
desired element in that nested list.
The output shown above is generated as 7 because index i gives the fifth element of list1 which
is 4 passed as the argument to i and index j gives the second element in the nested list, with
argument as 1.
6.5 COPYING LISTS
Given a list, the simplest way to make a copy of the list is to assign it to another li s t.
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 list l. Therefore, any changes
made to either of them will be reflected in the other list.
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.
Very Short Answer Type Questions
a) A
b) Daman
c) Error
d) n
7. Suppose L= [“abc”, [6,7,8],3, ‘mouse’] consider the list and answer the following:
(i) L[3:]
(ii) L[: :2]
(iii) L[1:2]
(iv) L[1][1]
8. What will be the output of the following Pythoncode?
a) 11
b) 12
c) 21
d) 22
6.6.1 append( )
append( ) method adds a single item to the end of the list. It doesn't create a new list; rather it
modifies the original list. The single element can also be a list. The syntax of append() method
is :
Syntax:
list.append(item )
The item can be numbers, strings, another list, dictionary, etc.
Example 1:
Example 2:
A list can also be added to the above existing list. For example,
Example 3:
6.6.2 extend()
The extend() method adds one list at the end of another list. In other words, all the items of a
list are added at the end of an already created list.
Syntax:
Example 4:
6.6.3 insert( )
The insert() function can be used to insert an element/object at a specified index. This function
takes two arguments: the index where an item/object is to be inserted and the item/ element
itself.
Syntax:
list_name.insert(index_number, value)
where,
list_name: is the name of the list
index_number: is the index where the new value is to be inserted
value: is the new value to be inserted in the list
Example 5:
6.6.4 reverse( )
The reverse( ) function in Python reverses the order of the elements in a list This function
reverses the item of the list. It replaces a new value "in place" of an item that already exists in
the list, i.e., 1t does not create a new list.
Example :
6.6.5 index( )
index() function in Python returns the index of first matched item from the list. It returns the
first occurrence of an item for which the index position is to be searched for in the list. If the
element is not present, ValueError is generated.
Syntax:
List.index(<item>)
Example :
6.6.7 len( )
len() function returns the length of the list.
Example :
6.6.8 sort( )
This function sorts the items of the list, by default in ascending/increasing order. This
modification is done "in place", i.e., it does not create a new list.
Syntax:
List.sort()
Example 13:
Example 14:
For string elements in a list, sorting is done on the basis of their ASCII values. Python starts
by comparing the first element from each element. If they are equal, it goes on to the next
element, and so on, until it finds elements that differ. Subsequent elements are not considered
(even if they are really big). It sorts the string in a lexicographic manner. If we want to sort the
list in decreasing order, we need to write:
>>>list1.sort (reverse=True)
Example 15:
6.6.9 clear( )
The clear() method removes all items from the list. This method doesn't take any parameters.
The clear() method only empties the given list. It doesn't return any value.
Example 16:
6.6.10 count( )
count() method counts how many times an element has occurred in a list and returns it.
The syntax of count() method is :
list.count(element)
Example 17:
Example 18:
7. DELETION OPERATION
Python provides operator for deleting/removing an item from a list. There are many
methods for deletion: If index is known, you can use pop() or del statement.
If the element is known, not the index, remove() can be used.
To remove more than one element, del() with list slice can be used.
1. pop( ):
It removes the element from the specified index and also returns the element which was
removed.
Syntax:
List.pop(index)
Example:
2. del statement
del statement removes the specified element from the list but does not return thedeleted value.
Note: If an out of range Index is provided with del() and pop(), the code will result in runtime
error.
The above del statement shall remove 2nd and 3rd elements from the list. As we know that
slice selects all the elements up to 4th index, so 4th element will remain in the list.
4. remove()
remove() function is used when we know the element to be deleted, not the index of the
element.
6.8 SEARCHING LIST
Lists can easily be searched for values using the index method that expects a value that is to be
searched. The output is the index at which the value is kept.
Syntax:
List_name.index(element)
Example:
Example:
max( )
Returns the element with the maximum value from the list.
Note: To use the max() function, all values in the list must be of the same type.
Example:
>>> list3= [10, 20 ,30,40]
>>> max (list3)
40
Example:
>>>list4= [‘A’, ‘a’, ‘B’, ‘C’]
> > > max (list4)
‘a’
Here, it will return the alphabet with the maximum ASCII value.
Example:
>>> list5= [‘ashwin’, ‘bharat’, ‘shelly’]
>>>max(list5)
‘shelly’
Here, it will return the string which starts with character having the highest ASCII value.
Example:
>>> list5= [‘ashwin’, ‘bharat’, ‘shelly’, ‘supreet’]
>>>max(list5)
‘supreet’
If there are two or more strings which start with the same character then the second character
is compared and so on.
min()
Returns the element with the minimum value from the list.
Note: To use the min() function, all values in the list must be of the same type.
Example:
>>> list3= [10, 20 ,30,40]
>>> min (list3)
10
Example:
>>>list4= [‘A’, ‘a’, ‘B’, ‘C’]
> > > min (list4)
‘A’
Here, it will return the alphabet with the minimum ASCII value.
Example:
>>> list5= [‘ashwin’, ‘bharat’, ‘shelly’]
>>>min(list5)
‘ashwin’
Here, it will return the string which starts with character having the smallest ASCII value.
Practical Implementation 1:
Write a Python script to input a number and count the occurrences of that number in a given list.
list1=[l0, 20, 30, 40, 10, 50, 10]
Output:
Practical Implementation 2:
Write a Python script to input a number and perform linear search.
Output:
Very Short Answer Type Questions
a) True
b) False
c) Error
d) None
1. myList = [1, 5, 5, 5, 5, 1]
2. max = myList[0]
3. indexOfMax = 0
4. for i in range(1, len(myList)):
5. if myList[i] > max:
6. max = myList[i]
7.indexOfMax = i 8.
9. >>>print(indexOfMax)
a) 1
b) 2
c) 3
d) 4
Short Answer Type Questions
9. What is the difference between extend ( ) and append ( )?
10. What is the difference between pop( ) and remove( )?
11. Write the output of the following:
L =[ ]
L1 = [ ]
L2= [ ]
for i in range(6,10):
L.append(i)
for i in range (10,4,-2):
L1.append(i)
for i in range (len(L1)):
L2.append(L[i]+L1[i])
L2.append(len(L)- len(L1))
print(L2)
Long Answer Type Questions
12. WAP to accept integer array and search a particular value in the array. If it exists, then
the function should display “exists”, otherwise should display “Does not exist”.
13. WAP that takes the list ‘L’ as an argument, adds 5 in all the odd values and 10 in all
the even values of the list. Also display the list.
14. Write a python script to calculate mean of the elements of an inputted list.
Revision Module
QUESTIONNAIRE
Very Short Answer Type Questions
1. myList = [1, 2, 3, 4, 5, 6]
2. for i in range(1, 6):
3.myList[i - 1] = myList[i] 4.
5. for i in range(0, 6):
6. print(myList[i], end = " ")
a) 2 3 4 5 6 1
b) 6 1 2 3 4 5
c) 2 3 4 5 6 6
d) 1 1 2 3 4 5
1. >>>list1 = [1, 3]
2. >>>list2 = list1
3. >>>list1[0] = 4
4. >>>print(list2)
a) [1, 3]
b) [4, 3]
c) [1, 4]
d) [1, 3, 4]
12. What will be the output of the following Python code?
a) None
b) 1
c) 2
d) Error
a) None
b) a
c) b
d) c
a) 4
b) 5
c) 8
d) 12
16. Write the most appropriate list method to perform the following tasks:
(i) Delete a given element from a list.
(ii) Get the position of an item in the list.
(iii) delete the 3rd element from the list.
(iv) Add single element at the end of the list.
(v) Add an element in the beginning of the list.
(vi) Add elements in the list at the end of a list.
17. Write the output of the following:
L1= [500,600]
L2= [35,45]
L1.append(700)
L1.extend(L2)
L1.insert(5,2)
print(L1)
print( L1 + L2)
print (L1. index(35))
print(L2 * 2)