
List Manipulation in Python | CBSE Class 11 | Computer Science
Dear Class 11th STUDENTS, ! Welcome to this tutorial of List Manipulation in Python from your CBSE class 11 of Computer Science Syllabus .
In this tutorial, we shall be learning our chapter-6: List Manipulation in Python from Unit 2: Programming and Computational Thinking (PCT-1) as CBSE BOARD suggested to learn about computer system and its organisation to complete this section.
Unit 2: Programming and Computational Thinking (PCT-1)
Chapter 11 : List Manipulation in Python:
- Introduction,
- Indexing,
- List operations (concatenation, repetition, membership and slicing), traversing a list using loops, built-in functions/methods–len(), list(), append(), extend(), insert(), count(), index(), remove(), pop(), reverse(), sort(), sorted(), min(), max(), sum();
- Nested lists,
- suggested programs: finding the maximum, minimum, mean of numeric values stored in a list; linear search on list of numbers and counting the frequency of elements in a list.
I advice you to check the latest syllabus given by CBSE Board at its Official website: www.cbseacademic.nic.in
Also, in this tutorial we will covers all necessary topics/concepts required to complete your exams preparations in CBSE classes 11th.
Also, you can Sign Up our free Computer Science Courses for classes 11th and 12th.
NOTE:
- We are also giving some important Questions & Answers for better understanding as well as preparation for your examinations.
- You may also download PDF file of this tutorial from our SHOP for free.
- For your ease and more understanding, we are also giving the video explanation class of each and every topic individually, so that you may clear your topics and get success in your examinations.
INTRODUCTION
The lists in python are containers that are used to store a list of any type. Unlike other variable Python lists are mutable i.e., you can change the elements of a list in place; Python will not create. A fresh list when you make changes to an element of a list is a type of sequence like strings and tuples but it differs from them in the way that lists are mutable but strings and tuples are immutable.
This tutorial is dedicated to basic list manipulation in Python. We shall be talking about creating and accessing lists, various list operations and list manipulation through some built-in functions.
CREATING AND ACCESSING LISTS
A list is a standard data type of Python that can store a sequence of values belonging to any type. The Lists are depicted through square brackets, e.g., following are some lists in Python:
[] # list with no member, empty list
[1, 2, 3] # list of integers
[1, 2, 5, 3. 7, 9] # list of numbers (integers and floating point)
[ ‘a’, ‘b’, ‘c’] # list of characters
[ ‘a’, 1, ‘b’, 3.5, ‘zero’] # list of mixed value types
[ ‘one’, ‘Two’, ‘Three’] # list of strings
Before we proceed and discuss how to create lists, one thing that must be clear is that Lists are mutable (i.e., modifiable) i.e., you can change elements of a list in place. In other words, the memory address of a list will not change even after you change its values. List is one of the two mutable types of Pythons – List and Dictionaries are mutable types; all other data types of Python are immutable.
Creating Lists
To create a list, put a number of expressions in square brackets. That is, use square brackets indicate the start and end of the list, and separate the items by commas. For example:
[ 2, 4, 6]
[‘abc’, ‘def’]
[1, 2.0 3, 4.0]
[ ]
Thus, to create a list you can write in the form given below:
L = [ ]
L = [ value, …]
This construct is known as a list display construct.
Consider some more examples:
- The empty list
The empty list is [ ]. It is the list equivalent of 0 or ‘‘and like them it also has truth value as false. You can also create an empty list as :
L = list ()
It will generate an empty list and name that list as L.
- Long lists
If a list contains many elements, then to enter such long list, you can split it across several lines, like below:
Sqrs = [ 0,1, 4, 9 ,16, 25, 36, 49, 64, 81, 100, 121, 144, 169,
196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625]
Notice the opening square bracket and closing square brackets appear just in the beginning and end of the list.
- Nested lists
A list can have an element in it, which itself is a list. Such a list is called nested list, e.g.,
L 1 = [3, 4, [5, 6], 7]
L1 is a nested list with four elements: 3,4, [5,6] and 7. L1 [2] element is a list [5,6].
Length of L1 is 4 as it counts [5,6] as one element. Also, as L1[2] is a list (i.e., [5,6]),
which means L1[2][0] will give5 and L1 [2][1] will give 6.
Creating Lists from Existing Sequences
You can also use the built -in list type object to create lists from sequences as per the syntax
Given below:
L = list (<sequence>)
where <sequence> can be any kind of sequence object including strings, tuples, and lists.
Python creates the individual elements of the list from the individual elements of passed Sequence. If you pass in other list, the list function makes a copy.
Consider following examples:
You can use this method of creating lists of single characters or single digits via keyboard input. Consider the code below:
Notice, this way the data type of all characters entered is string even though we entered digits. To enter a list of integers through keyboard, you can use the method given below.
Most commonly used method to input lists is eval (input ()) as shown below:
when you execute it , will work somewhat like :
Enter list to be added : [67, 78, 46, 23]
List you entered : [67, 78, 46, 23 ]
Please note, sometimes (not always) eval() does not work in Python Shell. At that time, you can run it through a script or program too.
Accessing Lists
Lists are mutable (editable) sequence having a progression of elements. There must be a way to access its individual elements and certainly there is. But before we start accessing individual elements, let us discuss the similarity of Lists with strings that will make it very clear to you how individual elements are accessed in lists- the way you access string elements. Following subsection will make the things very clear to you, I bet! 😊
Similarity with Strings
Lists are sequences just like strings that you have read in previous tutorial String Manipulation in Python.
They also index their individual element, just like strings do.
Thus, you can access the list elements just like you access a string’s elements e.g.,
List[i] will give you the element at i th index of the list;
List[a-b] will give you elements between indexes a to b-1 and so on.
Put in another words, Lists are similar to strings in following ways :
Length
Function len (L) returns the number of items (count) in the list L.
Indexing and slicing
L [i] returns the item at index i (the first item has index 0), and L[i:j] returns a new list, containing the objects at indexes between i and j (excluding index j ).
Membership operators
Both ‘in’ and ‘not in’ operators work on Lists jut like they work for other sequences. That is, in tells if an element is present in the list or not, and not in does the opposite.
Concatenation and replication operators + and *
The + operators adds one list to the end of another The * operator repeats a list. We hall be talking about these two operations in a later section 11.3 – List Operations.
Accessing individual Elements
As mentioned, the individual elements of a list are accessed through their indexes. Consider following examples:
>>> vowels = [ ‘a’, ‘e’, ‘I’, ‘o’, ‘u’]
>>> vowels [ o ]
‘a’
>>> vowels [4]
‘u’
>>> vowels [ -1]
‘u’
>>> vowels [-5]
‘a’
Like strings, if you give index outside, he legal indices (o to length -1 or – length – length +1,…. Uptill-1) while accessing individual elements, Python will raise index Error (see below)
Difference from strings
Although lists are similar to string in many ways, yet there is an important difference in mutability of the two. Tuple are not mutable, while lists are. You cannot change individual elements of a string in place, but lists allow you to do so. That is, following statement is fully valid for (through not for strings) :
L [i] = element
For example, consider the same vowels list created above, that stores all vowels in lower case. Now, if you want to change some of these vowels, you may write something as shown below:
Traversing a List
Recall that traversal of sequence means accessing and processing each element of it. Thus traversing a tuple also means the same and same is the tool for it, i.e.; the python loops. That is why sometimes we call a traversal as looping over a sequence.
The for loop makes it easy to traverse or loop over the items in a list, as per following syntax:
For < item> in < Tuple> :
process each item here
For example, following loop shows each item of a tuple T in separate lines :
T = (‘p’, ’y’, ‘t’, ‘h’, ‘o’, ‘n’)
for a in L
print ( [a] )
The above loop will produce result as:
P
y
t
h
o
n
How it works
The loop variable a in above loop will be assigned the Tuple elements, one at a time. So, loop- variable a will be assigned ‘p’ in first iteration and hence ‘p’ will be printed; in second iteration, a will get ‘y’ and ‘y’ will be printed; and so on.
If you only need to use the indexes of elements to access them, you can use functions range ( ) and len ( ) as per following syntax:
For index in range (len (L)):
process list [index] here
Consider following program that traverse through a tuple using above format and prints each item of a list L in separate lines along with its index.
program to print elements of a list [‘q’, ‘w’, ‘e’, ‘r’, ‘t’, ‘y’] in separate lines along with element’s both indexes (positive and negative).
L= [‘q’, ‘w’, ‘e’, ‘r’, ‘t’, ‘y’]
length = len (L)
for a in range (length):
print (“At indexes”, a, “and”, (a- length), “element:”, L [a] )
Sample run of above program is :
At indexes 0 and -6 element: q
At indexes 1 and -5 element: w
At indexes 2 and -4 element: e
At indexes 0 and -3 element: r
At indexes 4 and -6 element: t
At indexes 5 and -1 element: y
Comparing Lists
You can compare two lists using standard comparison operators of python, i.e., <, >, ==, !=, etc. python internally compares individual elements of lists (and tuples in lexicographical order. This means that to compare equal, each corresponding element must compare equal and the two sequence must be of the same type i.e., having comparable types of values.
Consider following examples:
Python raised error above because the corresponding second elements of lists i.e., L1 [1] and L3 [1] are not of comparable types. L1 [1] is integer (2) and L3 [1] is a list [2, 3] and list and numbers are not comparable types in python.
Python gives the final result of non-equality comparisons as soon as it gets a result in terms of True/False form corresponding elements’ comparison. If corresponding elements 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 ). See below
Table 11.1 Non-equality comparison in list sequences
So, for comparison purposes, python internally compares individual elements of two lists, applying all the comparison rules that you have read earlier. Consider following code:
There is also a cmp ( ) function that can be used for sequences’ comparisons but we are not covering it here.
LIST OPERATION
The most common operations that you perform with lists include joining lists, replicating lists and slicing lists. In this section ,we are going to talk about the same .
Joining Lists
Joining two lists is very easy just like you perform addition, Literally: -] . The concatenation operator +, when used with two lists. Consider the example given below:
As you can see that the resultant list has firstly elements of first list lst 1 and followed by elements of second list lst 2 . You can also join two or more lists to form a new list, example.
The + operator when used with lists requires that both the operands must be of list types. You cannot add a number or any other value to a list. For example, following expression will result in to error:
list + number
list + complex – number
list +string
Consider the following examples
Repeating or Replicating Lists
Like strings, you can use *operator to replicate a list specified number of times, example,
(considering the same list lst 1 = [1, 3, 5 ] )
Like strings, you can only use an integer with a * operator when trying to replicate a list.
Slicing the Lists
List slices, like string 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. Recall that index on last limit is not included in the list slice . The list slice is a list in itself, that is you can perform all operations on it just like you perform on lists
Consider the following example:
For normal indexing, if the resulting index is outside the list , python raises an IndexError exception. Slices are treated as boundaries instead and the result will simply contain all items between the boundaries. For the start and stop given beyond list limits in a list slice (I.e., out of bounds), python simply returns the elements that fall between specified boundaries, if any , without raising any error .
for example, consider the following
lists also support slice steps . That is , if you want to extract not consecutive but every other elements of the list , there is a way out –the slice steps . The steps are used as per following format:
seq = L [ start : stop : step ]
consider some examples to understand this.
Consider some more examples :
seq = L [: : 2 ] # get every other item , starting with the first
seq = L [5: : 2 ] # get every other item , starting with the sixth element , i. e ., index 5like strings ,
if you give < List name > [ : : 1] , it will reverse the list e. g., for a list say list = [5, 6, 8, 11, 3, ] following expression will reverse it :
>>> list [ : : _1 ]
[ 3, 11, 8, 6, 5, ] see, list reversed
Using Slices for list Modification
You can use slices to overwrite one or more list elements with one more other elements following examples will make it clear to you:
In all the above examples, we have assigned new values in the form of a sequence. The values being assigned must be a sequence, i.e., a list or string or tuple etc.
For example, following assignment is also valid.
But here, you should also know something. If you give a list slice with range much outside the length of the list, it will simply add the values at the end
Example
WORKING WITH LISTS
Now that you have learnt to access the individual elements of a list, let us talk about how you can perform various operations on lists like: appending, updating, deleting etc.
Appending Elements to a list
You can also add items to an existing sequence. The append ( ) method adds a single item to the end of list. It can be done as per following format:
L . append (item)
Consider some examples:
Updating Elements to a list
To update or change an element of the list in place, you just have to assign new value to the element’s index in list as per syntax:
L. [index] = <new value>
Consider following examples:
Deleting Elements from a list
You can also remove items from lists. The del statement can be used to remove an individual item, or to remove all items identified by a slice. It is to be used as per syntax given below:
Del List [<index>] # to remove element at index
del List [<start> : <stop> ] # to remove element in list slice
Consider following examples:
If you use del <lstname> only e.g., del lst, it will delete all the elements and the list object too. After this, no object by the name lst would be existing.
You can also use pop ( ) method to remove single element, not list slices. The pop ( ) method removes an individual item and returns it. The del statement and the pop method do pretty much the same thing, except that pop method also returns the removed item along with deleting it from list. The pop ( ) method is used as per following format:
List . pop ( < index>) # index optional ; if skipped, last element is deleted
Consider examples below
>>>lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15,
16, 17, 18, 19, 20]
>.. lst.Pop ( )
20
>>> lst.pop (10)
11
The pop ( ) method is useful only when you want to store the element being deleting for later use, example
item1 = L.pop ( ) # last item
item1 = L.pop ( 0 ) # first item
item1 = L.pop ( 5 ) # sixth item
Now you can use item 1, item2, and item3 in your program as per your requirement.
LIST FUNCTIONS AND METHODS
Python also offers many built –in functions and method for list manipulation. You have already worked with one such method len ( ) in earlier chapters. In this chapter, you will learn about many other built –in powerful list methods of python used for list manipulation.
Every list object that you create in python is actually an instance of list class (you need not do anything specific for this, python does it or you –you know built –in ). The list manipulation methods that are being discussed below can be applied to list as per following syntax:
< list object> . <Method name > ( )
In the following examples, we are referring to <list Object > as list only (no angle brackets but the meaning is intact i.e., you have to replace list with a legal list (i.e., either a list literal or a list object that holds a list).
The index method
This function returns the index of first matched item from the list. It is used as per following format:
List . index( <item>)
The append method
As you have read earlier in section 11.4 that the append ( ) method adds an item to the end of the list. It works as per following syntax:
List append ( < item > )
- Takes exactly one element ( a list type ) and returns no value
For example, to add a new item “yellow” to a list containing colors, you may write:
The extend method
The extend ( ) method is also used for adding multiple elements ( given in the form of a list ) to a list But it is different from append ( ) . first , let us understand the working of extend ( ) function then we ’ ll talk about the difference between these two functions.
The extend ( ) function works as per following format
List . extend ( < list > )
- Takes exactly one element ( a list type ) and returns no value
That is extend ( ) takes a list as an argument and appends all of the elements of the argument list to the list object on which extend ( ) is applied .
consider following example :
The above example left list t2 unmodified. Like append ( ) , extend ( ) also does not return any value .
Consider following example:
Difference between append ( ) and extend ( )
While append ( ) function adds one element to a list, extend ( ) can add multiple elements from a list supplied to it as argument .consider the following example that will make it clear to you :
Insert method
The insert ( ) method is also an insertion method for lists, like append and extend methods. However, both append ( ) and extend ( ) insert the elements (s ) at the end of the list . if you want to insert an element somewhere in between or any position of your choice , both append ( ) and extend ( ) are of no use . For such a requirement insert ( ) is used.
Insert ( ) function inserts an item at a given position. It is used as per following syntax:
List. Insert ( <pos >, <item >)
Takes two arguments and returns no value .
The first argument <pos> is the index of the element before which the second argument < item > is to be added.
Consider the following example:
For function insert (), we can say that
If, however, index is less than zero and not equal to any of the valid negative indexes of the list (depends on the size of the list ) , the object is prepended, i.e., added in the beginning of list e.g., for a list t1 = [‘a’, ‘e’, ‘I’, ‘u’ ], if we do :
>>> t1 . insert (-9, ‘k’ ) # valid negative indexes are -1, -2, -3, -4,
>>> t1
[‘k’ , ‘a’ , ‘e’ , ‘I’ , ‘u’ ] # list prepended with element ‘k’
Pop method
You have read about this method earlier. The pop ( ) is used to remove the item from the list. It is used as per following syntax :
list . pop (< index >) # <index is optional argument
– Takes one optional argument and returns a value – the item being deleted
Thus pop () removes an element from the given position in the list , and return it . If no index is specified, app ( ) removes and returns the last item in the list .consider some examples :
The pop ( ) method raises an exception (runtime error ) if the list is already empty . consider this example:
Remove method
While pop ( ) removes an element whose position is given , what if know the value of the element to be removed , but you do not know its index or position in the list ?well python thought it in advance and made available the remove ( ) method .
the remove ( ) method removes the first occurrence of given item from the list .It is used as per following format :
list . Remove (< value >) – takes one essential argument and does not return anything
The remove ( ) will report an error if there is no such item in the list . consider some examples :
Clear method
This method removes all the items from the list and the list becomes empty list after this function. This function returns nothing. It is used as per following.
list. clear ()
for instance, if you have a list L1 as
Unlike del <last-named> statement, clear ( ) removes only the elements and not the list element.
After clear ( ) , the list object still exists as an empty list.
The count method
This function returns the count of the item that you passed as argument. If the given item is not in the list, it returns zero . It is used as per following format :
List . Count ( <item >)
for instance , for a list L1 = [13, 18, 20, 10, 18, 23, ]
The reverse method
The reverse () reverses the items of the list . this is done “in place” , i.e., it does not create now list . the syntax to use reverse method is:
List. reverse () -Takes no argument, returns no list; reverse the list ‘in place’ and does not return anything .
for example,
The sort method
The sort () function sorts the items of the list , by default in increasing order , this is done “in place ” , I.e., it does not create a new list . it is used as per following syntax:
List. sort
for example,
>>> t1 = [‘e’, ‘I’, ‘q’, ‘a’, ‘q’, ‘p’]
>>> t1. Sort ()
>>> t1 #sorted list in default ascending order
[‘a’, ‘e’, ‘I’, ‘p’, ‘q’, ‘q’]
like reverse () , sort ( ) also performs its function and does not anything.
to sort a list in decreasing order using sort ( ), you can write :
>>> List . Sort (reverse = true)